5.1 Pair 和 Tuple

标准库第一版c++98引入tuple class,允许tuple带有最多10个类型不同的元素
c++11 采用variadic template概念,tuple可用于任意大小的异质集合(heterogeneous collection)
class pair中为两个元素服务,用于组合一个双元素的tuple

pair

于头文件<utility>

操作函数描述
pair<T1, T2> paDefault构造函数建立一个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 <<"]";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值