stl中pair容器的用法

 有时候,要用pair的时候就会忘记了,又得重新翻资料,所以在blog中总结一下

简而言之pair就是一个结构体,但是比结构体更加得灵活


template <class T1, class T2> struct pair //模板, T1, T2,可以是不同的类型


构造函数

<strong>#include<iostream>
using namespace std;
#include<string>
//#include <utility>  
int main()
{
	pair<int, string> p1; //default constructor 
	pair<string, double>p2("zhouyu", 100); // overroad constructor
	pair<string, double>p3 = (p2);
	p2.first = "nobody"; p2.second = 20;
	cout << p2.first << " " << p2.second << endl;
	cout << p3.first << " " << p3.second << endl;
	return 0;
} </strong>



重载运算符“=”,和makepair的用法

#include<iostream>
using namespace std;
#include<string>
//#include <utility>  
int main()
{
	pair<string, double> p1 = make_pair("tianyu", 100);
	pair<string, double> p2;
	p2 = p1; //overoad "="
	cout << p2.first << " " << p2.second << endl;
	return 0;
} 

pair类的比较函数:


pair<class first,class second> p;

说明:pari的比较是按照字典序比较的,还有就是先比较first,frist的值大的时候,pair就打

如果first相等,再比较second,second大的就pair打,如果first,second都一样,等于就成立

可以验证一下,下面程序输出的结果

//#include <utility>     
#include <iostream>    
using namespace std;
int main ()
{
  std::pair<int,char> A (10,'z');
  std::pair<int,char> B (90,'a');

  if (A==B) std::cout << "foo and bar are equal\n";
  if (A!=B) std::cout << "foo and bar are not equal\n";
  if (A< B) std::cout << "foo is less than bar\n";
  if (A>B) std::cout << "foo is greater than bar\n";
  if (A<=B) std::cout << "foo is less than or equal to bar\n";
  if (A>=B) std::cout << "foo is greater than or equal to bar\n";

  return 0;
}

其他有些函数和属性是c++11的标准,有些灵活,估计用的不多,还有就是有些编译器不能通过,所以没有列出来!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值