头文件:<tuple>
可访问属性:
无(用get方法来访问数据)
可访问方法:
swap(tuple) | 和另外一个tuple交换值 |
其他相关方法:
swap(t1, t2) | 交换两个tuple |
make_tuple(v1,v2..) | 创建一个tuple |
get<?>(tuple) | 访问数据 |
tie(v1, v2..) | 创建由reference构成的tuple |
例子:
例子1:构造tuple
tuple<int, float, string> t0; tuple<, 2.0, "three"); auto t2 = make_tuple(, , "asdf", 3.2); tuple<, "kaima")); //use pair to init tuple auto t4 = t1; tuple<, "John");
例子2:访问数据
tuple<, 2.0, "three"); cout << >(t1) << >(t1) << >(t1) << endl;
例子3:关系比较
tuple<, 2.0, "three"); tuple<, 1.0, "kaima"); if(t1 > t2) // >= < <= == != cout << "t1 > t2" << endl;
例子4:交换值
swap(t1, t2); t1.swap(t2);
例子5:reference构成的tuple
string s = "Hello"; tuple<string&> t1(s); >(t1) = "t1"; cout << s << endl; //t1 auto t2 = make_tuple(ref(s)); >(t2) = "t2"; cout << s << endl; //t2 auto t3 = tie(s); >(t3) = "t3"; cout << s << endl; //t3
其他:
(1)“接受不定个数的实参”的构造函数被声明为explicit。
(2)元素个数:tuple_size<tupleType>::value
(3)第idx个元素的类型:tuple_element<idx, tupleType>::type
(4)连接tuple:tuple_cat(t1, t2..)
额外:
使用以下代码可以直接cout一个tuple。
template <int IDX, int MAX, typename... Args> struct PRINT_TUPLE { static void print(ostream& strm, const tuple<Args...>& t) { strm << ==MAX ? "" : ","); PRINT_TUPLE<IDX+, MAX, Args...>::print(strm, t); //recursion } }; //end the recursion template <int MAX, typename... Args> struct PRINT_TUPLE<MAX, MAX, Args...> { static void print(ostream& strm, const tuple<Args...>& t) { //null } }; template <typename... Args> std::ostream& operator << (ostream& strm, const tuple<Args...>& t) { strm << "["; PRINT_TUPLE<, sizeof...(Args), Args...>::print(strm, t); return strm << "]"; }