C++11_ tuple

版权声明:本文为博主原创文章,未经博主允许不得转载。

tuple 是一个可以装载任何变量的容器,C++11的Variadic Templates给tuple的实现带来了极大方便.

tuple的实现基于递归继承,例如

std::tuple<int, float, string> t (41,6.3,"nico");

 结构图如下图

递归继承的优点是,将内存分配在连续片段上,这是在内存管理上非常好的做法

下面来介绍一下tuple的使用

std::tuple<int, float, string> t (1,2.5,"C++");
std::cout << sizeof(t) <<std::endl; //至于为啥是 32一直没弄懂
std::cout << get<0>(t) <<std::endl;
std::cout << get<1>(t) <<std::endl;
std::cout << get<2>(t) <<std::endl;

  输出结果

sizeof(tuple) 输出tuple的参数个数

get<num>(tuple) 获取第几个元素(num)


简单的创建

//make_tuple<>
auto t1 = make_tuple(22,44,"zi");
std::cout << sizeof(t1) <<std::endl;
std::cout << get<0>(t1) <<std::endl;
std::cout << get<1>(t1) <<std::endl;
std::cout << get<2>(t1) <<std::endl;

 输出结果


tuple的直接赋值

//tuple的赋值
auto t1 = make_tuple(22,44,"zi");
get<0>(t1) = get<1>(t1); //直接赋值,但是要求变量类型相同
std::cout<< get<0>(t1) << std::endl;

 输出结果


tie()的使用

//tie 捆绑  a,b,c 捆绑在t1的三个值上
 auto t1 = make_tuple(22,44,"zi");
 int a;
 int b;
 string c;
 tie(a,b,c) = t1;
 cout << a << endl;

输出结果


重新定义

//重新定义
typedef tuple<int, float, string> TupleType;//重命名
cout << tuple_size<TupleType>::value<< endl; //输出Tuple内的元素个数
tuple_element<1, TupleType> :: type f = 10; //去tuple的第一个元素类型去声明变量
cout << f <<endl;
typedef tuple_element<1, TupleType> :: type INT;//将Tuple的第一个元素的类型重新命名
INT g = 10;
cout << g << endl;

 输出结果

以上是C++11 tuple的基本使用 

如有不正确的地方请指正

参照<<侯捷 C++新标准 C++11>>

原文地址:https://www.cnblogs.com/LearningTheLoad/p/7231812.html