C++ pair 用法

來源:互聯網
上載者:User

標籤:ace   first   else   scan   include   訪問   pre   合成   algo   

轉載自 :http://www.cnblogs.com/handsomecui/p/4946151.html

 

 

pair 預設對first升序,當first相同時對second升序;

類模板:template <class T1, class T2> struct pair

參數:T1是第一個值的資料類型,T2是第二個值的資料類型。

功能:pair將一對值組合成一個值,這一對值可以具有不同的資料類型(T1和T2),兩個值可以分別用pair的兩個公有函數first和second訪問。

具體用法:

1.定義(構造):

1     pair<int, double> p1;  //使用預設建構函式2     pair<int, double> p2(1, 2.4);  //用給定值初始化3     pair<int, double> p3(p2);  //拷貝建構函式

2.訪問兩個元素(通過firstsecond):

1     pair<int, double> p1;  //使用預設建構函式2     p1.first = 1;3     p1.second = 2.5;4     cout << p1.first << ‘ ‘ << p1.second << endl;

輸出結果:1 2.5

3.賦值operator =

 

(1)利用make_pair

 

1     pair<int, double> p1;2     p1 = make_pair(1, 1.2);

(2)變數間賦值:

 

    pair<int, double> p1(1, 1.2);    pair<int, double> p2 = p1;

 

可以用cmp數組改;

代碼:

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#define mem(x,y) memset(x,y,sizeof(x))using namespace std;typedef long long LL;const int INF=0x3f3f3f3f;pair<int,int>pa[100];int cmp(pair<int,int>a,pair<int,int>b){    if(a.first!=b.first)return a.first>b.first;    else return a.second<b.second;}int main(){    int a,b;    for(int i=0;i<5;i++)scanf("%d%d",&a,&b),pa[i]=make_pair(a,b);    sort(pa,pa+5,cmp);    for(int i=0;i<5;i++)printf("%d %d\n",pa[i].first,pa[i].second);    return 0;}

 

C++ pair 用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.