#include "stdafx.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; struct Node { char id; int value; Node(char i, int v) : id(i), value(v) {} Node() : id(0), value('z') {} }; int main() { tuple t(32, "Penny wise", 'a'); tuple t = {32, "Penny wise", 'a'}; // 编译不过,构造函数是explicit的 cout << get<0>(t) << endl; cout << get<1>(t) << endl; cout << get<2>(t) << endl; get<1>(t) = "Pound foolish"; cout << get<1>(t) << endl; string& s = get<1>(t); s = "Patience is virtue"; cout << get<1>(t) << endl; //get<3>(t); // 编译不过,t只有3个字段 // get<1>(t) 类似于vector中的t[1] int i = 1; //get(t); // 编译不过,i必须是编译时常数 tuple t2; // 默认构造 t2 = tuple(12, "Curiosity kills the cat", 'd'); t2 = make_tuple(12, "Curiosity kills the cat", 'd'); if (t > t2) { // 词典比较 cout << "t is larger than t2" << endl; } t = t2; // 逐成员拷贝 // Tuple可以储存引用!! 诸如vector这样的STL容器不能。 Pair也可以 string st = "In for a penny"; tuple t3(st); //auto t3 = make_tuple(ref(st)); // 同上 get<0>(t3) = "In for a pound"; // st has "In for a pound" cout << st << endl; t2 = make_tuple(12, "Curiosity kills the cat", 'd'); int x; string y; char z; std::make_tuple(std::ref(x), std::ref(y), std::ref(z)) = t2; // 将t2赋值给to x, y, z std::tie(x,y,z) = t2; // 同上 std::tie(x, std::ignore, z) = t2; // 好处是tie可以有选择,get<1>(t2) is ignored // 其他特性 auto t4 = std::tuple_cat( t2, t3 ); // t4是t2和t3级联之后的结果tuple cout << get<3>(t4) << endl; // "In for a pound" // 类型特征 type traits cout << std::tuple_size::value << endl; // Output: 4 std::tuple_element<1, decltype(t4)>::type dd; // dd是string类型 } // tuple vs struct tuple getNameAge() { return make_tuple("Bob", 34); } int main() { struct Person { string name; int age; } p; tuple t; cout << p.name << " " << p.age << endl; //用struct有利于代码review cout << get<0>(t) << " " << get<1>(t) << endl; //tuple方便 // 作为单次使用的结构来传输一组数据 string name; int age; tie(name, age) = getNameAge(); // 比较tuples tuple time1, time2; // hours, minutes, seconds if (time1 > time2) cout << " time1 is a later time"; // 多索引的map map, string> timemap; timemap.insert(make_pair(make_tuple(12, 2, 3), "Game start")); cout << timemap[make_tuple(2,3,4)]; unordered_map, string> timemap; // 数据换顺序Little trick int a, b, c; tie(b, c, a) = make_tuple(a, b, c); } //不要滥用tuple,一旦发现tuple一再使用,考虑定义struct