C++11引入了tuple(元组),tuple可以被看作是一个模板化的结构体,可以在定义时包含任意类型任意数量的成员。
可通过如下几种方式创建tuple:
tuple t1 = {1, 3.14, "hello"}; //直接创建tuple
tuple> t2 = {1, {2, 3}}; //创建带有vector的tuple
auto t3 = make_tuple("hi", 8); //通过make_tuple创建tuple
vector v = {1, 2, 3};
auto t4 = make_tuple("hi", v); //通过make_tuple创建带有vector的tuple
元组的元素也可以是引用或指针:
int a = 1;
int *pa = &a;
tuple t{a, pa};
auto w = make_tuple(ref(a), pa);
cout<(t)<<" "<<*get<1>(t)<(w)<<" "<<*get<1>(w)<(t)<<" "<<*get<1>(t)<(w)<<" "<<*get<1>(w)<
可以通过get函数读取tuple指定索引(起始为0)元素的值:
tuple t1 = {1, 3.14, "hello"};
auto s = get<2>(t1); //取出索引2的元素
cout<
可以通过tuple_size获取元组中元素的数量:
tuple t1 = {1, 3.14, "hello"};
int num = tuple_size::value;
cout<
通过tuple_element或tuple_element_t,可以获得元组中某个索引元素的类型:
tuple t1 = {1, 3.14, "hello"};
cout<::type, int>::value<::type 的方便别名
cout<, int>::value<
可见通过tuple_element获得的t1的第0个元素的类型是int
可以通过tuple_cat,将多个tuple拼接为一个:
tuple t1 = {1, 3.14};
tuple, string> t2 = {{1,2,3}, "hi"};
auto t3 = tuple_cat(t1, t2);
int num = tuple_size::value;
cout<
可以通过tie,将元组里的元素解构到相应的变量中:
tuple t1 = {1, 3.14};
int a = 0;
double b = 0;
tie(a, b) = t1;
cout<
在解包时可以通过ignore忽略掉不关心的元素:
tuple t1 = {1, 3.14, "hello"};
string s;
tie(ignore, ignore, s) = t1;
cout<