STL 源碼分析 # stl_pair #

STL 源碼分析 # stl_pair #



pair是一種很簡單也很常用的關聯容器(associative container).



/***********************************************
Programmer	:	EOF
Date		:	2015.04.10
File		:	pair.cpp
E-mail		:	[email protected]

***********************************************/

#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函數其實本質上也就是調用了構造函數....













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章