tuple<> 模板是 pair 模板的泛化,但允许定义 tuple 模板的实例,可以封装不同类型的任意数量的对象,因此 tuple
实例可以有任意数量的模板类型参数。tuple 模板定义在 tuple 头文件中。
意思就是类似pair模板一样,pair模板只能有两个参数,但是tuple模板可以有好多个。
以下所有用到的函数都是tuple头文件里的
- 初始化
tuple<string,int,char> my_tuple[10];
my_tuple[0] = std::make_tuple ("Piper",42,'a');
- 获取值
cout << get<int>(my_tuple[0]); //用类型获取,但是类型不能定义的有同样的,不然会编译错误
cout << get<1>(my_tuple[0]); //用下标获取,从0开始,类型可以定义同样的
int a=1,b=2,c=3;
auto tp = tie(a, "aa", b); //tp的类型实际是:std::tuple<int&,string&, int&>
cout << get<0>(tp);
int x=5,y=5;
tie(x,ignore,y)=tp;
cout << x << y;
通过tie解包后,tp中三个值会自动赋值给三个变量。
解包时,我们如果只想解某个位置的值时,可以用std::ignore占位符来表示不解某个位置的值。比如我们只想解第三个值时:
std::tie(std::ignore,std::ignore,y) = tp; //只解第三个值了
- tuple_cat() 函数
std::tuple<int, string, float> t1(10, "Test", 3.14);
int n = 7;
auto t2 = tuple_cat(t1, make_pair("Foo","bar"), t1, tie(n));
n = 10;
cout << get<8>(t2) << endl;
输出10是因为tie是引用的
- 获取长度
int size = tuple_size<decltype(t2)>::value;
cout << size << endl;
decltype是获得()参数里面的变量的类型
- tuple_element
auto my = std::make_tuple (10,'a');
std::tuple_element<0,decltype(my)>::type first = std::get<0>(my); // 前面可以直接用auto替代
std::tuple_element<1,decltype(my)>::type second = std::get<1>(my);
std::cout << "mytuple contains: " << first << " and " << second << '\n';
- forward_as_tuple: 用于接受右值引用数据生成tuple
string str ("John");
auto out = [](tuple<string,int> t){cout << get<0>(t) << get<1>(t) << endl;};
out(forward_as_tuple(str+" Daniels",22));
out(forward_as_tuple(str+" Smith",25));
- tuple比较
tuple 对象中的元素是按照字典顺序比较的
只有所有元素全部相等两个tuple才相等
auto t3=t1;
cout << (t1<t3) << endl;
cout << (t1==t3) << endl;
- tuple交换
tuple<int, std::string, float> t4(11, "Test", 3.14);
cout << get<0>(t3) << " " << get<0>(t4) << endl;
t3.swap(t4);
cout << get<0>(t3) << " " << get<0>(t4) << endl;
- 排序
bool cmp(tuple<string,int,char> a,tuple<string,int,char> b){
return a<b;
return get<1>(a)<get<1>(b); // 也可以按某列排序
}
main(){
tuple<string,int,char> my_tuple[10];
my_tuple[0] = std::make_tuple ("Pipr",42,'a');
my_tuple[1] = std::make_tuple ("Piper",41,'a');
my_tuple[2] = std::make_tuple ("Pper",45,'a');
my_tuple[3] = std::make_tuple ("Pier",49,'a');
for(int i=0;i<4;++i){
cout << get<0>(my_tuple[i]) << " " << get<1>(my_tuple[i]) << " ";
}
cout << endl;
sort(my_tuple,my_tuple+4,cmp);
for(int i=0;i<4;++i){
cout << get<0>(my_tuple[i]) << " " << get<1>(my_tuple[i]) << " ";
}
cout << endl;
}
官方文档:http://www.cplusplus.com/reference/tuple/