tuple是一个“快速而随意”的数据结构,当我们希望将一些数据组合成单一对象而又不想麻烦的重新定义一个数据结构时,就可以使用tuple。
tuple定义在头文件<tuple>
中。tuple是类似pair又更泛化的模板,不像pair成员数量固定为2个,一个tuple可以有任意个类型不同的成员。
#include<iostream>
#include<tuple>
#include<string>
#include<vector>
using namespace std;
//举例用函数
typedef tuple<string, int, string> Personinfo;
vector<Personinfo> buildInfo()
{
string name, phoneNum;
int age;
vector<Personinfo> v;
while (cin >> name >> age >> phoneNum)
{
v.push_back(make_tuple(name, age, phoneNum));
}
return v;
}
int main()
{
//定义和初始化
tuple<int, int, long>tup1; //调用tuple的默认构造函数来值初始化成员,3个成员都为0
tuple<int, int, long>tup2 = { 1 ,2, 3 }; //C++ primer说此初始化是错误的,vs2015编译通过
tuple<int, int, long>tup3{ 2 ,0 ,0 };
auto tup4 = make_tuple(1, "abc", 3.0);//使用make_tuple函数生成tuple对象
cout << typeid(tup4).name() << endl; //class std::tuple<int, char const * __ptr64, double>
//访问tuple成员:get<i>(tup)
auto first_ele = get<0>(tup4); cout << typeid(first_ele).name() << " " << first_ele << endl; //int 1
auto second_ele = get<1>(tup4); cout << typeid(second_ele).name() << " " << second_ele << endl; //char const * __ptr64 abc
auto third_ele = get<2>(tup4); cout << typeid(third_ele).name() << " " << third_ele << endl; //double 3
//两个辅助模板类,模板实参必须是类型名而不是变量名
//查询tuple的成员数量:
typedef decltype(tup4) tup4_type;
size_t sz = tuple_size<tup4_type>::value; //tup4_type这种类型初始化tuple_size模板,返回其value成员
cout << sz << endl; // 3
//查询tuple的成员类型:
tuple_element<0, tup4_type>::type i = get<0>(tup4); //0和tup4_type初始化tuple_element模板,访问其type成员,i是int型
// tie: 用于拆开tuple,配合类型查询模板使用
tuple_element<0, tup4_type>::type a;
tuple_element<1, tup4_type>::type b;
tuple_element<2, tup4_type>::type c;
std::tie(a, b, c) = tup4;
cout << a << " " << b << " " << c << endl; // 1 abc 3
//forward_as_tuple: 用于接受右值引用数据生成tuple
auto tup5 = std::forward_as_tuple(1, "hello");
cout << typeid(tup5).name() << endl; //class std::tuple<int && __ptr64,char const (& __ptr64)[6]>
//tuple_cat: 用于连接tuple
auto tup6 = tuple_cat(tup3, tup4);
cout << typeid(tup6).name() << endl; //class std::tuple<int,int,long,int,char const * __ptr64,double>
//这里留下一个坑,怎么遍历tuple,大体思路是借助变参数模板的递归调用,有时间再研究
//比较两个tuple:成员数量首先必须相等才能比较,对每一对成员使用的判等或比较运算符必须合法
cout << boolalpha
<< (tup2 == tup3) << " " //false
<< (tup2 < tup3) << endl; //true,可见是从前往后逐成员比较,由靠前位置成员的大小关系决定
//tuple用途:返回多个值
vector<Personinfo> v = buildInfo();
for (auto it = v.begin(); it != v.end(); ++it)
{
cout << get<0>(*it) << " "
<< get<1>(*it) << " "
<< get<2>(*it) << endl;
}