标签:
头文件:<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<int, float, string> t1(1, 2.0, "three"); auto t2 = make_tuple(2, 2, "asdf", 3.2); tuple<int, string> t3(make_pair(1, "kaima")); //use pair to init tuple auto t4 = t1; tuple<int, string> t5 = make_pair(1, "John");
例子2:访问数据
tuple<int, float, string> t1(1, 2.0, "three"); cout << get<0>(t1) << " : " << get<1>(t1) << " : " << get<2>(t1) << endl;
例子3:关系比较
tuple<int, float, string> t1(1, 2.0, "three"); tuple<int, float, string> t2(1, 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); get<0>(t1) = "t1"; cout << s << endl; //t1 auto t2 = make_tuple(ref(s)); get<0>(t2) = "t2"; cout << s << endl; //t2 auto t3 = tie(s); get<0>(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 << get<IDX>(t) << (IDX+1==MAX ? "" : ","); PRINT_TUPLE<IDX+1, 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<0, sizeof...(Args), Args...>::print(strm, t); return strm << "]"; }
标签:
原文地址:http://www.cnblogs.com/programmer-kaima/p/5173650.html