通用工具(2)---Tuple

Tuple作为pair的扩展,可以拥有任意数量的元素

tuple的操作

tuple也是能默认构造,拷贝构造,赋值,比较等,他们都支持隐式转换,使用make_tuple,其所有元素类型都是通过自动推导获得类型。使用get时候不允许运行期才传入索引值。

tuple<int,string,double> p(15,"test",15.0);
auto p2=make_tuple(15,"test",15.0);
get<0>(p) = get<0>(p2);//copy
if(p==p2)//比较

tuple元素的引用

tuple的元素允许使用引用类型,使用reference_wrapper<>函数对象和ref()(引用类型)和cref()(const 引用)函数,可以影响make_pair产生的类型。

std::string s;
auto x=std::make_tuple(s);
std::get<0>(x)="test";
auto x=std::make_tuple(ref(s));
std::get<0>(x)="test";

还能将tuple的值提取出来

std::tuple<int,string,double> p(15,"test",15.0);
int a;
string b;
double c;
std::make_tuple(ref(a),ref(b),ref(c))=p;

也可以使用tie()和std::ignore

std::tuple<int,string,double> p(15,"test",15.0);
int a;
string b;
std::tie(a,b,std::ignore)=p;

tuple和初值列

为了避免一个单一元素被转换为带着一个元素的tuple,所以在tuple中使用初值列是不允许隐式转换的。如果你尝试将一个初值列赋值或者返回值给tuple(将初值列传入一个期望获得tuple的地方)将会报错

std::tuple<int,string,double> p{15,"test",15.0};//ok
std::tuple<int,string,double> p2={15,"test",15.0}//error
std::vector<std::tuple<int,int>> v{{10,20},{30,40}};//error
std::vector<std::tuple<int,int>> v{make_tuple(10,20),make_tuple(30,40)};

tuple其他特性

std::tuple_size<p>::value//获得tuple元素的个数
std::tuple_element<0,p>::type//获得p的第一个元素的类型
auto t=std::tuple_cat(p,p2);//将tuple p和p2串接成新的tuple t

猜你喜欢

转载自blog.csdn.net/qq_35651984/article/details/83721413