1. 程式人生 > >stl中pair容器的用法

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的標準,有些靈活,估計用的不多,還有就是有些編譯器不能通過,所以沒有列出來!