技術在於交流、溝通,本文為博主原創文章轉載請注明出處並保持作品的完整性
在前面我介紹過一次tuple,今天在書上也看到了tuple,那就在寫一次吧.
tuple(元組),他的內部可以放任意類型的變量(有點類似結構體),前面介紹過它的遞歸繼承,這次直接看基本使用吧
1.創建和取出元素
void testTuple() { tuple<string, int, int, complex<double>> t; tuple<int, float, string> t1(41, 6.3, "nico"); auto t2 = make_tuple(22,44,"make_tuple"); //operator= get<1>(t1) = get<1>(t2); //取出指定下標元素 get<index>(tuple) cout << "testTuple operator=: " << get<1>(t1) << endl; }
2.比較大小 : 比較原則為,先比較元素個數,然后按其元素的比較規則比較大小(比較大小的兩個tuple,所含元素類型必須相同)
void testTupleCompare() { tuple<int, float, string> t1(41, 6.3, "nico"); auto t2 = make_tuple(22,44,"make_tuple"); if(t1 < t2) cout<< "testTupleCompare t1 < t2" << endl; else cout << "testTupleCompare t1 > t2" << endl; }
3.分割元素 tie()
void testTupleTie() { tuple<int, float, string> t1(41, 6.3, "nico"); int a; int b; string str; tie(a,b,str) = t1; cout << "testTupleTie a="<< a << " b=" << b << " str="<< str << endl; }
4.tuple_size和tuple_element(取出元素類型)
void testTupleSizeAndElement() { tuple<int, float, string> t(41, 6.2, "nico"); cout << "testTupleSizeAndElement tuple_size = " << (tuple_size<decltype(t)>::value) << endl;//取出tuple元素個數 typedef tuple_element<0,decltype(t)>::type T1;;//取出tuple元素類型 typedef tuple_element<1,decltype(t)>::type T2; typedef tuple_element<2,decltype(t)>::type T3; cout << "index[0] element: " << typeid(T1).name()<<endl << "index[1] element: " << typeid(T2).name()<< endl << "index[2] element: " << typeid(T3).name() << endl; }
5.拼接tuple tuple_cat
void testTupleCat() { tuple<int> t1(41); auto t2 = make_tuple(22); auto t3 = tuple_cat(t1,t2); cout << __FUNCTION__ << " t3: " << get<0>(t3) << " " << get<1>(t3) << endl; }
6.交換函數 swap()
void testTupleSwap() { tuple<int> t1(41); auto t2 = make_tuple(22); t1.swap(t2); cout << __FUNCTION__ << " t1 " << get<0>(t1) << endl; cout << __FUNCTION__ << " t2 " << get<0>(t2) << endl; }
參考侯捷<<STL源碼剖析>>