標籤:copy height code str const c++編程 pop data swap
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> inlinevoid swap(pair<_Ty1, _Ty2>& _Left, pair<_Ty1, _Ty2>& _Right){// swap _Left and _Right pairs_Left.swap(_Right);}//推斷是否相等函數template<class _Ty1,class _Ty2> inlinebool operator==(const pair<_Ty1, _Ty2>& _Left,const pair<_Ty1, _Ty2>& _Right){// test for pair equalityreturn (_Left.first == _Right.first && _Left.second == _Right.second);//兩個元素都比較}//推斷是否不等函數template<class _Ty1,class _Ty2> inlinebool operator!=(const pair<_Ty1, _Ty2>& _Left,const pair<_Ty1, _Ty2>& _Right){// test for pair inequalityreturn (!(_Left == _Right));}//推斷是否小於函數template<class _Ty1,class _Ty2> inlinebool operator<(const pair<_Ty1, _Ty2>& _Left,const pair<_Ty1, _Ty2>& _Right){// test if _Left < _Right for pairsreturn (_Left.first < _Right.first ||!(_Right.first < _Left.first) && _Left.second < _Right.second);}//推斷是否大於函數template<class _Ty1,class _Ty2> inlinebool operator>(const pair<_Ty1, _Ty2>& _Left,const pair<_Ty1, _Ty2>& _Right){// test if _Left > _Right for pairsreturn (_Right < _Left);}//推斷是否小於等於函數template<class _Ty1,class _Ty2> inlinebool operator<=(const pair<_Ty1, _Ty2>& _Left,const pair<_Ty1, _Ty2>& _Right){// test if _Left <= _Right for pairsreturn (!(_Right < _Left));}//推斷是否大於等於函數template<class _Ty1,class _Ty2> inlinebool operator>=(const pair<_Ty1, _Ty2>& _Left,const pair<_Ty1, _Ty2>& _Right){// test if _Left >= _Right for pairsreturn (!(_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;
C++編程->pair(對組)