pair 是 一种模版类型。每个pair 可以存储两个值。这两种值无限制,可以是tuple,vector ,string,struct等等。
首先来看一下pair的函数
初始化,复制等相关操作如下:
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); |
// pair TEMPLATE FUNCTIONS
//交换函数
template<class _Ty1,
class _Ty2> inline
void swap(pair<_Ty1, _Ty2>& _Left, pair<_Ty1, _Ty2>& _Right)
{ // swap _Left and _Right pairs
_Left.swap(_Right);
}
//判断是否相等函数
template<class _Ty1,
class _Ty2> 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<class _Ty1,
class _Ty2> inline
bool operator!=(const pair<_Ty1, _Ty2>& _Left,
const pair<_Ty1, _Ty2>& _Right)
{ // test for pair inequality
return (!(_Left == _Right));
}
//判断是否小于函数
template<class _Ty1,
class _Ty2> 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<class _Ty1,
class _Ty2> inline
bool operator>(const pair<_Ty1, _Ty2>& _Left,
const pair<_Ty1, _Ty2>& _Right)
{ // test if _Left > _Right for pairs
return (_Right < _Left);
}
//判断是否小于等于函数
template<class _Ty1,
class _Ty2> inline
bool operator<=(const pair<_Ty1, _Ty2>& _Left,
const pair<_Ty1, _Ty2>& _Right)
{ // test if _Left <= _Right for pairs
return (!(_Right < _Left));
}
//判断是否大于等于函数
template<class _Ty1,
class _Ty2> inline
bool operator>=(const pair<_Ty1, _Ty2>& _Left,
const pair<_Ty1, _Ty2>& _Right)
{ // test if _Left >= _Right for pairs
return (!(_Left < _Right));
}
贴一段代码:
//pair 定义
pair<string,int>pair1;
//pair 定义以及赋值一
pair<string,int>pair2("lily",4);
pair<string,int>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<<pair2.first<<endl;
cout<<pair2.second<<endl;
//pair 输出方式二
cout<<get<0>(pair1)<<endl;
cout<<get<1>(pair1)<<endl;