STL源码分析之pair

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值