标准库第一版c++98引入tuple class,允许tuple带有最多10个类型不同的元素
c++11 采用variadic template概念,tuple可用于任意大小的异质集合(heterogeneous collection)
class pair中为两个元素服务,用于组合一个双元素的tuple
pair
于头文件<utility>
操作函数 | 描述 |
---|---|
pair<T1, T2> pa | Default构造函数建立一个pair,其元素分别为T1和T2,各自以其default构造函数初始化 |
pa.first | 获取pair内第一value(直接成员访问) |
pa.second | 获取pair内第二value(直接成员访问) |
std::get<0>(pa) | 等价于pa.first(C++11) |
std::get<1>(pa) | 等价于pa.second(C++11) |
std::make_pair(val1, val2) | 返回一个pair,带有val1和val2的类型和数值(无任何限定符的浮点字面常量的类型都被视为double) |
- c++11起,如果std::pair<>用到某个类型,而该类型只有一个nonconstant copy构造函数,将不再编译成功
- 支持隐式类型转换和move semantic搬迁first和second元素
tuple
于头文件<tuple>
操作 | 描述 |
---|---|
std::tuple<T1, T2, …, Tn> | 以n个给定类型的元素建立一个tuple,以各自类型default构造函数初始化(基础类型初值都为0) |
std::tuple<T1, T2> t(pair) | 建立一个带有2元素的tuple,以pair为初值(类型须吻合) |
std::make_tuple(v1, v2,…) | 以传入的所有数值和类型建立一个tuple |
std::tie(ref1, ref2, …) | 建立一个由reference构成的tuple |
std::string s;
auto x = std::make_tuple(s); //x is of type tuple<string>
auto y = std::make_tuple(ref(s)); //y is of type tuple<string&>,thus y refer to s
std::get<0>(y) = "my value"; //both y and s is "my value"
//使用tie
print_tuple.hpp,包含改文件的可直接使用ostream(std::cout)输出tuple类型数据
#include <tuple>
#include <iostream>
//hepler: print element with index IDX of tuple with MAX elements
template <int IDX, int MAX, typename... Args>
struct PRINT_TUPLE {
static void print (std::ostream& strm, const std::tuple<Args...>& t) {
strm << std::get<IDX>(t) << (IDX+1 == MAX ? "" : ",");
PRINT_TUPLE<IDX+1, MAX, Args...>::print(strm, t);
}
};
//paritial sepcilization to end the recursion
template <int MAX, typename... Args>
struct PRINT_TUPLE<MAX, MAX, Args...> {
static void print (std::ostream& strm, const std::tuple<Args...>& t) {
}
};
//output operator for tuples
template <typename... Args>
std::ostream& operator << (std::ostream& strm, const std::tuple<Args...>& t) {
strm <<"[";
PRINT_TUPLE<0, sizeof...(Args), Args...>::print(strm, t);
return strm <<"]";
}