九、 通用工具 ----pair 和Tuple---pair

来源:互联网 发布:js对象深拷贝 编辑:程序博客网 时间:2024/05/29 16:56

九、 通用工具

标签(空格分隔): c++STL


本章讲解c++标准库的通用工具,包括:

  • class pair<> 和 class tuple<>
  • smart pointer class(shared_ptr<>和unique_ptr<>)
  • 数值极值(Numeric limit)
  • Type trait 和TYPE utility
  • 辅助函数(如min(),.max()和swap())
  • class ratio<>
  • clock 和 timer
  • 若干重要的c函数

1 pair和tuple

1 pair

  1. 定义与头文件
  2. 将两个value视为一个单元
  3. 容器map、multimap、unordered_map和unordered_multimap使用pair管理key/value形式的元素

原型:

template <class T1, class T2> struct pair;

是一个结构体,所有成员都是public;

1.1 成员操作

pair的操作函数

1.2 构造函数和赋值

1.2.1 构造函数

函数原型;

//default (1)   constexpr pair();//copy / move (2)   template<class U, class V> pair (const pair<U,V>& pr);template<class U, class V> pair (pair<U,V>&& pr);pair (const pair& pr) = default;pair (pair&& pr) = default;//initialization (3)    pair (const first_type& a, const second_type& b);template<class U, class V> pair (U&& a, V&& b);//piecewise (4) template <class... Args1, class... Args2>  pair (piecewise_construct_t pwc, tuple<Args1...> first_args,                                   tuple<Args2...> second_args);

说明:
1. 默认构造函数
2. 拷贝和右值构造函数
3. 初始化
4. 构造成员first和second,将first_args的元素作为参数传递给第一个构造函数,将second_args的元素传递给第二个构造函数。这是两个“带有不确定参数个数”的tuple对象;但是【需要第一个实参:std::piecewise_construct_t 才能强迫执行这个构造函数】


1.2.2 make_pair()

  1. 无需类型就可以生成一个pair对象;
  2. 可能不如pair<>产生的对象类型明确
    例如:
//不需要: std::pair<int,char>(42,'0')std::make_pair(42,'0')//std::pair<int,float>(42,7.77)//生成的是(int,double)["无任何限定符的浮点字面常量被视为double"]make_pair(42,7.77)

1.2.3 pair之间的比较

(1).”==”

//x == yx.first == y.first && x.second == y.second

(2).”<”

  • 第一元素具有较高的优先级
  • first相等,才能继续比较second
// x< yx.first < y.first || (!(y.first<x.first) && x.second < y.second)
原创粉丝点击