0
点赞
收藏
分享

微信扫一扫

C++ stl 标准模板库Pair 元素绑定合成结构体

Villagers 2022-09-15 阅读 57


/*
1.pair的常用用法
pair:两个元素绑在一起作为一个合成元素,可以看成是两个元素的结构体
struct pair
{
typeName1 first;
typeName2 second;
};

2.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);

3.pair元素的访问
pair中只有两个元素,first和second
*/

/*
#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
pair<string,int>p;
p.first="hello";
p.second=3;
cout<<p.first<<" "<<p.second<<endl;

return 0;
}
*/

/*
4.pair常用函数
*/
/*
#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;
}
*/
/*
pair的用途
代替二元结构体
作为map的键值来进行插入操作
*/

#include <iostream>
#include <map>
#include <string>


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;
}



 

举报

相关推荐

0 条评论