• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Foreordination
酒后高歌磨剑,梦中快意恩仇,名利脚下踩,情义两肩挑
博客园    首页    新随笔    联系   管理    订阅  订阅
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

posted on 2018-09-25 14:56  Foreordination  阅读(7502)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3