就用法见注释,有需要可复制到编译器运行
#include <iostream>
#include <utility> //当然也可以用map
#include <string>
#include <map>
using namespace std;
//pair 可以理解为只含有两个元素的二元结构体(并非结构体),其节省了代码量
/*
pair<typename1,typename2> name;
定义时初始化 pair<string,int> p("hjy",17);
临时构建pair :(1)pair<string,int>("haha",01);
(2)make_pair("haha,01");
两个pair用>,<,==,!=,<=,>=比较时 先比较两个pair的第一个元素,在比较第二元素
pair的常见用途:
(1)用于代替二元结构体
(2)作为map的键值对 进行输入
*/
int main()
{
cout<<"用pair逐一遍历:"<<endl;
pair<string,int> p;
p.first = "hao";
p.second = 98;
map<string,int> mp;
mp.insert(p);
cout<< p.first <<" "<< p.second<<endl;
p = make_pair("jie",04);
mp.insert(make_pair("jie",04));
cout<< p.first <<" "<< p.second<<endl;
p = pair<string,int>("yun",07);
mp.insert(pair<string,int>("yun",07));
cout<< p.first <<" "<< p.second<<endl;
cout<<"用于mp迭代器遍历:"<<endl;
for(map<string,int>::iterator it = mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}