C++模板库STL——pair

总结:pair比较适合将两个不同类型的数据放在一块输入、输出(像一个小型结构体)
0、定义与访问

#include <iostream>
#include <utility>
#include <string>
using namespace std;

int main(){
	pair<string,int>p;
	p.first = "haha";
	p.second = 5;
	cout<<p.first<<" "<<p.second<<endl;
	p = make_pair("xixi",55);
	cout<<p.first<<" "<<p.second<<endl;
	p = pair<string,int>("heihei",555);
	cout<<p.first<<" "<<p.second<<endl;
	return 0;
}

1、pair函数,两个pair类型数据可以直接使用==/!= /</<=/>/>=比较,比较规则是先以first的大小作为标准,只有当first相等时才去判别second的大小

#include <stdio.h>
#include <utility>
using namespace std;

int main(){
	pair<int,int>p1(5,10);
	pair<int,int>p2(5,15);
	pair<int,int>p3(10,5);
	if(p1<p3){
		printf("p1<p3\n");
	}
	if(p1 <= p3){
		printf("p1<=p3\n");
	}
	if(p1<p2){
		printf("p1<p2\n");
	}
	return 0;
}

pair使用的例子:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main(){
	map<string,int>mp;
	mp.insert(make_pair("aeihei",5));
	mp.insert(pair<string,int>("haha",10));
	for(map<string,int>::iterator it = mp.begin();it != mp.end();it++){
		cout<<it->first<<" "<<it->second<<endl;//输出的顺序是默认按照first字典序升序来输出 
	}
	return 0;
}
发布了123 篇原创文章 · 获赞 3 · 访问量 3221

猜你喜欢

转载自blog.csdn.net/weixin_42377217/article/details/104094051