pair主要是用於map中,它的實現代碼很簡單,構造的操作也較少
#ifndef __SGI_STL_INTERNAL_PAIR_H
#define __SGI_STL_INTERNAL_PAIR_H
__STL_BEGIN_NAMESPACE
template <class T1, class T2>
struct pair
{
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& a, const T2& b) : first(a), second(b) {}
};
// 重載==操作符,只有當pair中的兩個成員均相等時才相等
template <class T1, class T2>
inline bool operator==(const pair<T1, T2>& x, const pair<T1, T2>& y)
{
return x.first == y.first && x.second == y.second;
}
//重載<操作符,要求x.first<y.first或者在前者相同的情況下,比較second
template <class T1, class T2>
inline 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);
}
// 至於爲什麼沒有提供operator !=, >, >=, <=
// 這個是因爲其在<stl_relops.h>中有實現, 其只依賴operator <和==
// 所以在此特化operator ==, <就能滿足要求
template <class T1, class T2>
inline pair<T1, T2> make_pair(const T1& x, const T2& y)
{
return pair<T1, T2>(x, y);
}
__STL_END_NAMESPACE
#endif
簡單應用
int main()
{
pair<int,int> p;
cout<<p.first<<" "<<p.second<<endl;
pair<int,int> p1(1,2);
cout<<p1.first<<" "<<p1.second<<endl;
pair<int,int> p2 = make_pair(3,4);
cout<<p2.first<<" "<<p2.second<<endl;
if(p2 >= p1)
cout<<"true"<<endl;
return 0;
}