C++ tuple

C++的tuple是一个可以存储不同类型元素的对象,类似于pair但包含更多元素。它允许在编译时通过get和tie函数访问元素。tuple与pair和array有交互,提供灵活的数据打包解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++ tuple

tuple 是将不同类型的元素打包在一个对象中的对象,就像 pair 对象对元素对所做的那样。

从概念上讲,tuple 类似于普通的旧数据结构(类似于 c 的结构体),但它没有指定数据成员,而是按 tuple 中的顺序访问元素。

tuple 中特定元素的选择是在模板实例化时完成的,因此,必须在编译时使用 get 和 tie 等辅助函数来指定。

tuple 与 pair (在头文件 <utility> 中定义)密切相关:元组可以由 pair 构造,pair 可以作为 tuple 来处理,以达到某些目的。

array 还具有某些类似元组的功能。(array 可以使用 get)

示例:

#include <iostream>
using namespace std;
template<int IDX, int MAX, typename... Args>
struct PRINT_TUPLE {
	static void print(ostream& os, const tuple<Args...>& t) {
		os << get<IDX>(t) << (IDX + 1 == MAX ? "" : ",");
		PRINT_TUPLE<IDX + 1, MAX, Args...>::print(os, t);
	}
};
template<int MAX, typename... Args>
struct PRINT_TUPLE<MAX, MAX, Args...> {
	static void print(std::ostream& os, const tuple<Args...>& t) {
	}
};
template<typename... Args>
ostream& operator<<(ostream& os, const tuple<Args...>& t) {
	os << "[";
	PRINT_TUPLE<0, sizeof...(Args), Args...>::print(os, t);
	return os << "]";
}
int main() {
	int ref1 = 1;
	tuple<int, string> a{ ref(ref1),"a" };//传引用进去
	auto b = make_tuple(2, "b", 2.2);
	get<1>(b) = "bbb";

	int x;
	string y;
	tie(x, y) = a;
	cout << "提取元素" << endl;
	cout << "a 中的元素:" << x << " " << y << endl;
	tie(x, y, ignore) = b;
	cout << "b 中的元素:" << x << " " << y << endl << endl;

	cout << "简易的交换元素" << endl;
	string t = get<1>(a);
	cout << "t:" << t << endl;
	get<1>(a) = get<1>(b);
	get<1>(b) = t.c_str();
	cout << "get<1>(a):" << get<1>(a) << endl;
	cout << "get<1>(b):" << get<1>(b) << endl << endl;

	cout << "查询 tuple 的大小:" << endl;
	cout << "a 的大小:" << tuple_size<decltype(a)>::value << endl;
	cout << "b 的大小:" << tuple_size<decltype(b)>::value << endl << endl;
	
	//对于提取值时,还是用 auto 声明变量比较好
	//标准方式太长了,而且也不好记
	tuple_element<0, decltype(a)>::type t1 = get<0>(a);
	auto t2 = get<0>(a);
	cout << t1 << " " << t2 << endl << endl;

	tuple<int, int, string> c{ 1,1,"1" };
	pair<int, string> d{ 2,"2" };
	auto e = tuple_cat(c, d);
	cout << "e 中的元素:";
	//无法使用 for
	//因为 get<size_t>(t) 的语法中是 size_t 必须在编译的时候确定,所以无法传左值。
	//所以重载操作符 << 吧
	cout << e;

	return 0;
}

输出:

提取元素
a 中的元素:1 a
b 中的元素:2 bbb

简易的交换元素
t:a
get<1>(a):bbb
get<1>(b):a

查询 tuple 的大小:
a 的大小:2
b 的大小:3

1 1

e 中的元素:[1,1,1,2,2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值