STL之pair源碼分析

來源:互聯網
上載者:User

直接進入主題,請看pair的源碼:

namespace std{template<typename T1,typename 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){}//建構函式,用a初始化first,用b初始化secondtemplate<typename U,typename V>     //模板函數,拷貝建構函式pair(const pair<U,V>& p):first(p.first),second(p.second){}};template<typename T1,typename T2>      //模板函數,操作符重載之==bool operator==(const pair<T1,T2>&,const pair<T1,T2>&);template<typename T1,typename T2>//  <符重載bool operator<(const pair<T1,T2>&,const pair<T1,T2>&);//還有!=,<=,>,>=省略了}

很簡單吧,注意,struct預設許可權是public的,這麼以來所有成員都是public的,我們因此可以直接存取pair中的個別值;

接下來再給大家帶來一個便捷的函數,make_pair()

namespace std{template<typename T1,typename T2>pair<T1,T2>make_pair(const T1& x,const T2& y){return pair<T1,T2>(x,y);}}

下面是兩個具體的運用:

#include<iostream>#include<string>#include<vector>using namespace std;int main(){vector<pair<string,int> >v;string name;int age;while(cin>>name>>age){v.push_back(make_pair(name,age));}for(vector<pair<string,int> >::iterator itera=v.begin();itera!=v.end();++itera){cout<<(*itera).first<<"----->"<<(*itera).second<<endl;}system("pause");return 0;}

#include<iostream>#include<string>#include<vector>using namespace std;int main(){pair<string,int>p1("zhang",22);pair<string,int>p2("zhan",22);cout<<(p1==p2)<<endl;cout<<(p1>p2)<<endl;cout<<(p1<p2)<<endl;p2.first="zhang";cout<<"****************"<<endl;cout<<(p1==p2)<<endl;cout<<(p1>p2)<<endl;cout<<(p1<p2)<<endl;system("pause");return 0;}

pair在標準函數庫用的特別多,尤其是map和multimap

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.