STL原始碼分析之pair結構體
阿新 • • 發佈:2018-12-08
前言
前面在分析set, RB-tree都有在insert實現中出現pair
, 下節分析map
的時候更會經常出現pair, 所以打算在之前先對pair有個認識.
pair
是一個有兩個變數的結構體, 即誰都可以直接呼叫它的變數, 畢竟struct預設許可權都是public, 將兩個變數用pair
繫結在一起, 這就為map<T1, T2>提供的儲存的基礎.
pair操作
pair結構是在map
標頭檔案裡面, 直接使用pair例項化可以修改任意元素, 而map對first
設定為了const
, 所以不能修改鍵值.
int main()
{
pair< string, int> pa[3];
pa[0].first = "one", pa[0].second = 1;
pa[1].first = "two", pa[1].second = 2;
pa[2].first = "three", pa[2].second = 3;
for(const auto &i : pa)
cout << i.first << " " << i.second << endl;
// one 1
// two 2
// three 3
pa[0].first = "zero", pa[0] .second = 0;
for(const auto &i : pa)
cout << i.first << " " << i.second << endl;
// zero 0
// two 2
// three 3
exit(0);
}
pair分析
pair的實現很簡單, 結構體封裝了兩個變數, 過載了==與<運算子, 也提供了建構函式.
pair結構定義
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) {}
#ifdef __STL_MEMBER_TEMPLATES
template <class U1, class U2>
pair(const pair<U1, U2>& p) : first(p.first), second(p.second) {}
#endif
};
過載
因為只有兩個變數, 運算子過載也很簡單
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);
}
make_pair
根據兩個數值構造一個pair.
template <class T1, class T2>
inline pair<T1, T2> make_pair(const T1& x, const T2& y) {
return pair<T1, T2>(x, y);
}
總結
整體pair的功能與實現都是很簡單的, 這都是為map的實現做準備的, 下節我們就來分析map的實現.