STL 源码分析 # stl_pair #
pair是一种很简单也很常用的关联容器(associative container).
/***********************************************
Programmer : EOF
Date : 2015.04.10
File : pair.cpp
E-mail : jasonleaster@gmail.com
***********************************************/
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
pair<int, int> int_pair(100, 200);
pair<string, int> si_pair("hello world", 42);
pair<string, string> ss_pair("jason", "leaster");
cout << int_pair.first << " " << int_pair.second << endl;
cout << si_pair.first << " " << si_pair.second << endl;
cout << ss_pair.first << " " << ss_pair.second << endl;
return 0;
}
很难得啊...pair数据类型的数据成员居然不是私有成员~
我们看看pair的实现:
这是我到目前为止在STL里面看到的最简单的数据抽象... ...
支持的各种比较运算符:
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;
}
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);
}
#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER
template <class _T1, class _T2>
inline bool operator!=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) {
return !(__x == __y);
}
template <class _T1, class _T2>
inline bool operator>(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) {
return __y < __x;
}
template <class _T1, class _T2>
inline bool operator<=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) {
return !(__y < __x);
}
template <class _T1, class _T2>
inline bool operator>=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) {
return !(__x < __y);
}
而make_pair函数其实本质上也就是调用了构造函数....