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;
}