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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM