五、pair用法
头文件:#include< utility >
1.pair 默认对first升序,当first相同时对second升序;
类模板:template <class T1, class T2> struct pair
参数:T1是第一个值的数据类型,T2是第二个值的数据类型。
功能:pair将一对值组合成一个值,这一对值可以具有不同的数据类型(T1和T2),两个值可以分别用pair的两个公有函数first和second访问。
pair实际上可以看作一个内部有两个元素的结构体,且这两个元素的类型是可以指定的
struct pair{
typename1 first;
typename2 second;
};
2…定义(构造):
pair<int, double> p1; //使用默认构造函数
pair<int, double> p2(1, 2.4); //用给定值初始化
pair<int, double> p3(p2); //拷贝构造函数
2.访问两个元素(通过first和second):
pair<int, double> p1; //使用默认构造函数
p1.first = 1;
p1.second = 2.5;
cout << p1.first << ' ' << p1.second << endl;
3.赋值 :
//(1)利用make_pair:
pair<int, double> p1;
p1 = make_pair(1, 1.2);
//(2)变量间赋值:
pair<int, double> p1(1, 1.2);
pair<int, double> p2 = p1;
4.示例
#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模板类,包括其默认排序规则、构造方式、元素访问和赋值操作。示例中展示了如何使用pair进行排序和赋值,并提供了完整的代码实现。
1098

被折叠的 条评论
为什么被折叠?



