目錄
1、tuple
tuple擴展了pair將兩個元素看成一個單元的功能,實現了可以將任意數量元素當作一個單元的功能。
2、函數
tuple<T1,T2...Tn> t; 以n個給定類型的元素建立tuple
tuple<T1,T2...Tn> t(v1,v2...vn);建立tuple,並初始化
tuple<T1,T2> t(pair); 建立一個tuple,帶兩個元素
t = t2; 將值t2賦值給t
t = pair; 將pair 賦值給帶兩個元素的tuple
t1 == t2; 比較所有元素
t1 != t2
t1 < t2
t1 > t2
t1 <= t2
t1 >= t2
t1.swap(t2);
swap(t1,t2);
make_tuple(v1,v2...); 以傳入值類型建立tuple
tie(ref(1)...; 建立reference構成的tuple
3、測試
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
template<int Idx, int Max, typename... Args>
struct PRINT_TUPLE {
static void print(ostream &os, const tuple<Args...>& t)
{
os << get<Idx>(t) << (Idx + 1 == Max ? "" : ",");
//遞歸
PRINT_TUPLE<Idx + 1, Max, Args...>::print(os, t);
}
};
//遞歸的結束條件
template <int Max, typename... Args>
struct PRINT_TUPLE<Max, Max, Args...>
{
static void print(ostream &os, const tuple<Args...>& t)
{
}
};
//重載操作運算符<<
template <typename... Args>
ostream& operator << (ostream& os, const tuple<Args...>& t)
{
os << "[";
PRINT_TUPLE<0, sizeof...(Args), Args...>::print(os, t);
return os << "]";
}
int main()
{
//創建
tuple<int, char, string> t;
t = make_tuple(1, 'a', "ABC");
cout << get<0>(t) << ends << get<1>(t) << ends << get<2>(t).c_str() << endl;
//取值
int a = 0;
char ch1 = ' ';
string str;
tie(a, ch1, str) = t;
cout << a << ends << ch1 << ends << str.c_str() << endl;
//不允許這種操作,不允許隱式轉換
//vector<tuple<int, char, string>> v{ { 1, 'a', "ABC" },{ 2, 'b', "DEF" } };
cout << t << endl;
//獲取元素類型
tuple_element<0, decltype(t)>::type ages;
//獲取元素數目
cout << tuple_size<decltype(t)>::value << endl;
system("pause");
}