2 std::tuple(不定数的值组)
扩展了pair的概念,拥有任意数量的元素。
原型;
template <class... Types> class tuple;
2.1 tuple的操作
- make_tuple() : 创建一个tuple;
- get<>():访问tuple中的元素;
例子:
//产生一个tuple
tuple<int ,int, int , string> tu(1,2,3,"hello");
auto t2 = make_tuple(1,2,3,4"hello");
//tuple元素类型可以是引用
string s;
tuple<string&> t3(s);
get<0>(t3) = "hello"; //给s赋值, s="hello";
//运行期间传递索引不被运行
int i;
get<i>(t2) //编译时错误
get<5>(t2) //无效索引,编译时错误
- tie() : 建立元素为引用的tuple,可以从tuple中提取个别数值
例子:
int i ,j;
string s;
//建立一个tuple
std::tuple<int , int ,string> t(1,2,"hello");
//建立引用类型的tuple,从t中取值
tie(i,j,s) = t;//取了i,j,s的引用建立tuple,并且用t给他赋值
//---------------------------------
//使用std::ignore忽略某些元素
tie(i,std::ignore,s) =t;//t中的第一和第三个值给i,s赋值;
2.2 tuple和初始值列(Initializer List)
tuple的初始化构造函数中,“接受不定个数的实参”被声明为: explicit:
//initialization (4)
template <class... Types>
explicit tuple (const Types&... elems);
template <class... UTypes>
explicit tuple (UTypes&&... elems);
因此,tuple的初始化不能进行隐式转换;
因此,tuple的初始化不能使用赋值语法,这会被视为一个隐式转换:
tuple<int,int> t(1,2); //ok
tuple<int,int> t2 ={1,2}; //error
//明确的降初始值转为一个tuple
vector<tuple<int, int> > v = { make_tuple(1,2),make_tuple(1,2) };
2.3 tuple的其他特性
tuple的辅助函数:
tuple_size<tuple_type>::value
: 可获得tuple类型元素个数tuple_element<idx,tupletype>::type
: 可获得第idx个元素个数的类型,下标从零开始tuple_cat()
:可将多个tuple串接成一个tuple;
例子:
#include<typeinfo>
#include<tuple>
//-----------------------
typedef tuple<int, int, string> tupleType;
cout << "size: " << tuple_size<tupleType>::value << endl;
auto t = make_tuple(1, 2, "string");
cout << "Type: " << typeid(tuple_element<1,tupleType>::type).name() << endl;
结果为;
size: 3
Type: int
2.4 tuple的输入和输出
- tuple最初公开于boost程序库;
- 如果拥有
printtuple.hpp
,才可以使用“<<”输出
3 tuple和pair的转换
- 可以将一个pair作为初值初始化一个双值的tuple
- 也可以将tuple作为初值初始化一个pair
pair和tuple的构造函数:
pair (piecewise_construct_t pwc, tuple<Args1...> first_args,
tuple<Args2...> second_args);
//tuple
//conversion from pair (5)
template <class U1, class U2>
tuple (const pair<U1,U2>& pr);
template <class U1, class U2>
tuple (pair<U1,U2>&& pr);
例子:
//使用pair构造tuple
auto p = pair<int, string>(123,"hello");
auto t1 = tuple<int, string>(p);
//使用tuple构造pair
auto t2 = tuple<int, int>(123,456);
piecewise_construct_t pwc;//不传递任何信息,此参数的唯一目的是选择正确的构造函数签名。
auto p2 = pair<decltype(t1),decltype(t2)>(pwc, t1, t2);