C++标准模板库(STL)之 pair

pair是一种将两个元素绑在一起的容器,需要使用头文件:#include<utility>

1.定义:

pair<typename1,typename2> name;

初始化:

pair<string,int>p("hahaha",5);

2.pair元素的访问

示例:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<utility>
typedef long long LL;
using namespace std;


int main(){
    pair<string,int>p;
    p.first="hahaha";
    p.second=5;
    cout<<p.first<<" "<<p.second<<endl;
    return 0;
}
//输出:
//hahaha 5

3.pair常用函数

比较操作数:

两个pair类型数据可以直接使用==,!=,<,<=,>,>=比较大小

比较规则是先以first的大小作为标准,只有当first相等时才去判别second的大小

示例:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<utility>
typedef long long LL;
using namespace std;


int main(){
    pair<int,int>p1(5,10);
    pair<int,int>p2(5,15);
    if(p1<p2){
        printf("p1<p2\n");
    }else{
        printf("p1>p2\n");
    }
    return 0;
}
//输出:
//p1<p2

4.pair常见用途

(1)用来代替二元结构体及其构造函数,可以节省编码时间

(2)作为map的键值对来进行插入

posted @ 2021-01-25 14:53  XA科研  阅读(163)  评论(0编辑  收藏  举报