目录
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");
}