文件:Test.cppios
#include <iostream> #include <string> #include <tuple> using namespace std; void test_1() { cout << "test_1: ----------------------" << endl; // create and initialize a tuple explicitly tuple<int, float, string> t(41, 6.3, "nico"); cout << "tuple<int, float, string>, sizeof = " << sizeof(t) << endl; // iterator over elements cout << "t: " << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << endl; } void test_2() { cout << endl << "test_2: ----------------------" << endl; // create tuple with make_tuple() auto t = make_tuple(22, 44, "stacy"); cout << "t: " << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << endl; } void test_3() { cout << endl << "test_3: ----------------------" << endl; auto t1 = make_tuple(41, 6.3, "nico"); auto t2 = make_tuple(22, 44, "stacy"); // assign second value in t2 to t1 get<1>(t1) = get<1>(t2); cout << "get<1>(t1) = " << get<1>(t1) << endl; } void test_4() { cout << endl << "test_4: ----------------------" << endl; auto t1 = make_tuple(41, 6.3, "nico"); auto t2 = make_tuple(22, 44, "stacy"); // comparsion if (t1 < t2) { cout << "t1 < t2" << endl; } else { cout << "t2 < t1" << endl; } // assigns values for value t1 = t2; cout << "t1: " << get<0>(t1) << " " << get<1>(t1) << " " << get<2>(t1) << endl; cout << "t2: " << get<0>(t2) << " " << get<1>(t2) << " " << get<2>(t2) << endl; } void test_5() { cout << endl << "test_5: ----------------------" << endl; tuple<int, float, string> t(77, 1.1, "more light"); int il; float fl; string sl; // 批量賦值 // std::tie會將變量的引用整合成一個tuple,從而實現批量賦值。 tie(il, fl, sl) = t; cout << "il = " << il << ", fl = " << fl << ", sl = " << sl << endl; } void test_6() { cout << endl << "test_6: ----------------------" << endl; typedef tuple<int, float, string> TupleType; cout << "tuple_size<TupleType>::value = " << tuple_size<TupleType>::value << endl; tuple_element<1, TupleType>::type fl = 1.1F; cout << "tuple_element<1, TupleType>::type fl : " << fl << endl; typedef tuple_element<1, TupleType>::type T; T fll = 1.1F; cout << "T fll : " << fll << endl; } ostream& operator<< (ostream &out, const tuple<int, float, string>& t) { cout << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << endl; } void test_7() { cout << endl << "test_7: ----------------------" << endl; auto t = make_tuple(41, 6.3, "nico"); cout << t; } int main() { test_1(); test_2(); test_3(); test_4(); test_5(); test_6(); test_7(); return 0; }
輸出:spa
test_1: ---------------------- tuple<int, float, string>, sizeof = 32 t: 41 6.3 nico test_2: ---------------------- t: 22 44 stacy test_3: ---------------------- get<1>(t1) = 44 test_4: ---------------------- t2 < t1 t1: 22 44 stacy t2: 22 44 stacy test_5: ---------------------- il = 77, fl = 1.1, sl = more light test_6: ---------------------- tuple_size<TupleType>::value = 3 tuple_element<1, TupleType>::type fl : 1.1 T fll : 1.1 test_7: ---------------------- 41 6.3 nico