C++标准库之 Pair

595 阅读2分钟

pair 在C++中是一个存储两个数据的容器,他是组成 map 的元素,下面先来看一下他的class 信息

template<typename _T1, typename _T2>
  struct pair
  {
    typedef _T1 first_type;    /// @c first_type is the first bound type
    typedef _T2 second_type;   /// @c second_type is the second bound type

    _T1 first;                 /// @c first is a copy of the first object
    _T2 second;                /// @c second is a copy of the second object
}

这里只是这贴出来了一小部分代码,不过从代码中可以看出来,他是一个模板类 也就是 java 中的泛型容器,在使用过程中需要指定 pair 中的模板类型

例子如下

正常写法
std::pair<int,std::string> p(10,"tsm");

但是由于这种写法比较刻板,而且需要书写的代码量比较多, C++的标准库给出了一个简单的写法

//简单写法
auto tsm_pair=std::make_pair(15,"11");

简写后不需要再指定数据类型了,非常的方便

使用 pair 中的元素也是非常简单的,下面使用打印的例子来获取 pair 中保存的数据

std::cout<< "打印 pair :"<<tsm_pair.first <<"  "<< tsm_pair.second <<std::endl;

使用它的数据就是使用他的first 与 second 即可

在 stl pair 包中,重写了 pair 的 == ,>, <, !=, 等方法,下面我们以 == 为例看一下

/// Two pairs of the same type are equal iff their members are equal.
template<typename _T1, typename _T2>
  inline _GLIBCXX_CONSTEXPR bool
  operator==(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y)
  { return __x.first == __y.first && __x.second == __y.second; }

可以看到在做比较的过程中是先比较的first ,然后在比较的second ,其他方法也是亦然

下面了一个比较的例子


std::pair<int,std::string> p(10,"tsm321");

std::pair<int , std::string> p1 (5,"tsm123");

bool result= p>p1 ;

std::cout<< "p是否大于p1:"<<result<<std::endl;

结果如下:

p是否大于p1:1

在pair 中还有一个 swap 交换的方法 ,那就是将一个 pair 的值交给另一个 pair,例子如下

std::pair<int , std::string> p1 (5,"tsm123");

std::pair<int , std::string> p2 (10,"1111");
p1.swap(p2);

std::cout<< "p1 swap 方法执行后的结果:"<<p1.first <<"  "<< p1.second <<std::endl;

结果如下:

p1 swap 方法执行后的结果:10  1111

p1.swap(p2); 的意思就是将 p2 的值赋值给 p1

到了这里 pair 的简单介绍就完成了