C++ std::pair

一 简介

定义于头文件<utility> 
template <class T1, class T2>
struct pair;

二 pair构造函数

// 大致3类
pair( const T1& x, const T2& y );

template< class U1, class U2 >
pair( U1&& x, U2&& y );

template< class... Args1, class... Args2 >
pair( std::piecewise_construct_t,
      std::tuple<Args1...> first_args,
      std::tuple<Args2...> second_args );

特别是第3个, 建立一个pair,以tuple first_args和second_args的元素为初值。下面例子重点说明第3个构造函数。

class A {
 public:
  A(std::tuple<int, float>) {
    std::cout << "A(std::tuple<int, float>)" << std::endl;
  }

  template <typename... Args>
  A(Args... args) {
    std::cout << "A(Args... args)" << std::endl;
  }
};


std::tuple<int, float> t(1, 2.2);
std::pair<int, A> p1(10, t);
std::pair<int, A> p2(std::piecewise_construct, std::make_tuple(100), t);

若A增加一个构造函数

class A {
 public:
  A(std::tuple<int, float>) {
    std::cout << "A(std::tuple<int, float>)" << std::endl;
  }

  template <typename... Args>
  A(Args... args) {
    std::cout << "A(Args... args)" << std::endl;
  }
  
  // 新增
  A(int, float) { std::cout << "A(int, float)" << std::endl; }
};

原因在于:std::piecewise_construct的存在,p2的第二个元素是以tuple t 的元素(int和float)而不是tuple整体来进行构造的。

三 C++11中的扩展

1. 取元素值

std::pair<int, int> p;
p.first;
p.second;

// C++11
std::get<0>(p);
std::get<1>(p);

2. 赋值运算符和移动赋值运算符,且允许隐式类型转换

3. swap函数

4. std::tuple_size<std::pair> 获得pair的大小(类模板特化) 

5. std::tuple_element<std::pair> 获得pair中元素的类型(类模板特化)

std::pair<int, double> p1;
std::cout << "p1.first : " << p1.first  << " p1.second : " << p1.second  << std::endl;
std::cout << "std::get<0>(p1) : " << std::get<0>(p1)  << " std::get<1>(p1) : " << 
     std::get<1>(p1)  << std::endl;

std::pair<int, const char*> p2(1, "hi");
std::pair<int, std::string> p3(2, "hell0");
std::pair<int, std::string> p4(3, "hey");
std::cout << "p3.first : " << p3.first  << " p3.second : " << p3.second  << std::endl;
p3 = p2;
std::cout << "p3.first : " << p3.first  << " p3.second : " << p3.second  << std::endl;
p3.swap(p4);
std::cout << "p3.first : " << p3.first  << " p3.second : " << p3.second  << std::endl;

std::pair<int, std::string> p5(std::piecewise_construct,
                               std::make_tuple(1),
                               std::forward_as_tuple(10, 'a'));
std::cout << "p5.first : " << p5.first  << " p5.second : " << p5.second  << std::endl;

std::cout << "p5 size : " << std::tuple_size<decltype(p5)>::value << std::endl;
  
std::tuple_element<0, decltype(p5)>::type; // int

 

四 参考

cppreference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值