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

1、Pair的常用用法

pair:两个元素绑在一起作为一个合成元素。可以看成是两个元素的结构体。

struct pair
{
    typeName1  first;
    typeName2 second;
};

1.1、pair的定义

添加头文件#include<utility>(#include<map>)和using namespace std;

map的内部设计到pair的使用,所以map头文件会自动添加#include<utility>头文件。

pair<typename1,typename2> name;

pair<string,int> p;
pair<string,int>("hello",1);

1.2、pair元素的访问

pair中只有两个元素,first和second。

#include<stdio.h>
#include<utility>

using namespace std;
int main()
{
    pair<string,int> p;
    p.first="hello";
    p.second=3;
    cout<<p.first<<" "<<p.second<<end;
    
    return 0;
}

1.3、pair常用函数

1.3.1、比较操作==,!=,<,<,<=,>,>=

比较的时候,显示比较first,first相等才比较second

#include<stdio.h>
#include<utility>

using namespace std;
int main()
{
    pair<int,int> p1(1,2);
    pair<int,int> p2(2,3);
    pair<int,int> p3(1,4);
    if(p1<p2)printf("p1<p2\n");
    if(p1<=p3)printf("p1<=p3\n");
    if(p2<p3)printf("p2<p3\n");    
    return 0;
}

1.4、pair的用途

代替二元结构体

作为map的键值来进行插入操作。

#include<stdio.h>
#include<map>

using namespace std;
int main()
{
    map<string,int> mp;
    mp.insert(pair<string,int>("help",1));
    mp.insert(make_pair("hello",2));
    for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }
    return 0;
}

 

2018-09-25 20:41:03

@author:Foreordination

原文链接: https://www.cnblogs.com/drq1/p/9699491.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/281842

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午5:59
下一篇 2023年2月15日 上午5:59

相关推荐