c++ tuple的操作

xiaoxiao2021-02-28  94

tuple(不定数值组)的操作 1.初始化 见Init()//class tuple<>构造函数是 explicit的,因此不支持隐式转换 2.其他tuple的特性 见special 3.tuple的输出 见output()等

#include<iostream> #include<tuple> using namespace std; void Init() { //常规初始化 tuple<int, double, string> t1(3, 3.14, "Wh");//... //用pair初始化tuple pair<int, double> p(2, 3); tuple<int, double> t2(p); //other int a = 3; double b = 3.14; //tie()更多见 tieIntuple() tuple<int&, double&> p3 = tie(a, b); auto p4 = make_tuple(ref(a), ref(b)); } void tieIntuple() { int a = 4; double b = 4.2; //tie返回的类型是tuple<int&,double&> tuple<int, double> p1 = tie(a, b); tuple<int&, double&> p2 = tie(a, b); --a; b = 5.3; cout << get<0>(p1) << ends << get<1>(p1) << endl; cout << get<0>(p2) << ends << get<1>(p2) << endl; //通过tie()得到特定位置的值 double d = 0.0; tie(ignore, d) = p2; cout << d << endl; } void special() { //得到类型个数 cout << tuple_size < tuple<int, double, double>>::value; //得到指定位置类型 tuple_element<1, tuple<int, double, double>>::type d = 3.14; cout << d << endl; //将多个tuple串接成一个tuple auto tp = tuple_cat(make_tuple(3.22, 3), tie(d)); } template<int Index,int Max,typename ...Args> struct PRINT_TUPLE { static void print(ostream& os, const tuple<Args...>& t) { os << get<Index>(t) << (Index + 1 == Max ? "" : ","); PRINT_TUPLE<Index + 1, Max, Args...>::print(os, t); } }; template<int Max,typename ...Args> struct PRINT_TUPLE<Max, Max, Args...> { //无实例调用必须声明为静态方法 static void print(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 << "]"; } void output() { tuple<int, double, double> t(3, 2.33, 3.22); cout << t; } int main() { //Init(); //tieIntuple(); //special(); output(); system("pause"); return 0; }
转载请注明原文地址: https://www.6miu.com/read-69392.html

最新回复(0)