Pair(队组)可以将两个值视为一个单元。C++标准程序库内多处使用了这个struct,尤其在容器map和multimap,就是使用pair来管理其键值/实值的成对元素。除此之外,任何函数需要返回两个值,也需要pair。
pair定义于<utility>
其部分声明如下
namespace std{
template <class T1,class T2>
struct pair{
//type names for the values
typedef T1 first_type;
typedef T2 second_type;
//member
T1 first;
T2 second;
//default constructor
pair():first(T1()),second(T2())
{ }
//constructor for two values
pair(const T1&a,const T2&b):first(a),second(b)
{ }
//copy constructor with implicit conversions
template<class U,class V>
pair(const pair<U,V> &p):first(p.first),second(p.second)
{ }
};
//comparisons
template<class T1,class T2>
bool operator==(const pair<T1,T2>&,const pair<T1,T2>&);
template<class T1,class T2>
bool operator< (const pair<T1,T2>&,const pair<T1,T2>&);
......
//convenience function to create a pair
template<class T1,class T2>
pair<T1,T2> make_pair(const T1&,const T2&);
}
- pair被定义为struct而不是class,表示其成员全部是public的,因此可以直接存取pair中的值。
- 利用default构造函数生成pair时,以两个”被该default构造函数个别初始化“的值作为初值,假如我们写了如下一行代码
pair<int,float> p;
我们就是利用了上述default构造函数以int(),float()来初始化p。
- pair之间的比较。如果两个pair对象内的所有元素都相等,则视为这两个pair对象相等。
template<class T1,class T2>
bool operator==(const pair<T1,T2>&x,const pair<T1,T2> &y)
{
return x.first==y.first && x.second==y.second;
}
假如两个pair对象进行比较时,第一元素不相等,其比较结果就成为整个比较的结果;如果第一元素相等,继续比较第二元素,并把比较结果作为整体比较结果。所以第一元素具有较高的优先级
template <class T1,class T2>
bool operator<(const pair<T1,T2> &x,const pair<T1,T2> &y)
{
return x.first < y.first || (!(y.first < x.first) && x.second<y.second);
}
- make_pair()函数使我们无需写出型别,就可以生成一个pair对象
template<class T1,classT2>
pair<T1,T2> make_pair(const T1 &x,const T2 &y)
{
return pair<T1,T2>(x,y);
}
因此我们可以直接写
make_pair(4,"hello")
而不必写成
pair<int,string>(4,"hello");
这里我们将前面提到的概念应用起来编写一段程序(源自于c.plusplus.com)
#include <utility> // std::pair, std::make_pair
#include <string> // std::string
#include <iostream> // std::cout
int main () {
std::pair <std::string,double> product1; // default constructor
std::pair <std::string,double> product2 ("tomatoes",2.30); // value init
std::pair <std::string,double> product3 (product2); // copy constructor
product1 = std::make_pair(std::string("lightbulbs"),0.99); // using make_pair (move)
product2.first = "shoes"; // the type of first is string
product2.second = 39.90; // the type of second is double
std::cout << "The price of " << product1.first << " is $" << product1.second << '\n';
std::cout << "The price of " << product2.first << " is $" << product2.second << '\n';
std::cout << "The price of " << product3.first << " is $" << product3.second << '\n';
return 0;
}

C++中的pair结构用于组合两个值为一个单元,常用于容器如map和multimap的键值对。pair有默认构造函数,可以接受两个值进行初始化,并提供了比较操作符。make_pair函数方便创建pair对象,无需显式指定类型。
1030

被折叠的 条评论
为什么被折叠?



