【STL学习】pair

转载自 :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
",pa[i].first,pa[i].second);
    return 0;
}
祝你早日攒够失望,然后开始新的生活。
原文地址:https://www.cnblogs.com/LuRenJiang/p/6918819.html