pair 是 一种模版类型。每个pair 可以存储两个值。这两种值无限制,可以是tuple,vector ,string,struct等等。
首先来看一下pair的函数
初始化,复制等相关操作如下:
| default (1) | constexpr pair(); |
|---|---|
| copy / move (2) | template
|
| initialization (3) | pair (const first_type& a, const second_type& b);
template
|
| piecewise (4) | template
|
// pair TEMPLATE FUNCTIONS //交换函数 templateinline void swap(pair<_Ty1, _Ty2>& _Left, pair<_Ty1, _Ty2>& _Right) { // swap _Left and _Right pairs _Left.swap(_Right); } //判断是否相等函数 template inline bool operator==(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) { // test for pair equality return (_Left.first == _Right.first && _Left.second == _Right.second);//两个元素都比较 } //判断是否不等函数 template inline bool operator!=(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) { // test for pair inequality return (!(_Left == _Right)); } //判断是否小于函数 template inline bool operator<(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) { // test if _Left < _Right for pairs return (_Left.first < _Right.first || !(_Right.first < _Left.first) && _Left.second < _Right.second); } //判断是否大于函数 template inline bool operator>(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) { // test if _Left > _Right for pairs return (_Right < _Left); } //判断是否小于等于函数 template inline bool operator<=(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) { // test if _Left <= _Right for pairs return (!(_Right < _Left)); } //判断是否大于等于函数 template inline bool operator>=(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) { // test if _Left >= _Right for pairs return (!(_Left < _Right)); }
贴一段代码:
//pair 定义 pairpair1; //pair 定义以及赋值一 pair pair2("lily",4); pair pair3(pair2); //pair 赋值方式二 pair1=make_pair(string("tom"),3); //pair 赋值方式三 pair1.first="jim"; pair1.second=2; //pair 赋值方式四 get<0>(pair1)=string("jim"); get<1>(pair1)=6; //pair 赋值方式五 swap(pair1,pair3); //pair 输出方式一 cout< (pair1)< (pair1)<