c++ 中pair类模板的用法详解

pair:

头文件:#include<utility>

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

参数:T1是第一个值的数据类型,T2是第二个值的数据类型。

功能:pair将一对值组合成一个值,这一对值可以具有不同的数据类型(T1和T2),两个值可以分别用pair的两个公有函数first和second访问。

具体用法:

1.实例化:

  


   pair<string,string> p1("hello","word"); //调用default constructor
   pair<double,int>    p2(1.0,1);//调用constructor
   pair<double,int>    p3(p2); //调用 copy

2.对象的赋值以及make_pair()的应用:

     pair<string,string> p1;
     pair<string,string> p2("good","good");
     p1= p2;
     p1= make_pair("hello","word");
     p1 = pair<string,string>("nice","nice");


3.pair中元素的访问(first & second):


     pair<double,int>    p1(1.0,2);
     pair<string,string> p2("hello","word");
     int i = p1.second;  // i = 2
     double d = p1.first; // d = 1.0
     string s1 = p2.first; // s1 = hello
     string s2 = p2.second; // word



4.pair数组与元素排序:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
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;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值