C++中的pair

pair的類型c++

    pair 是 一種模版類型。每一個pair 能夠存儲兩個值。這兩種值無限制。也能夠將本身寫的struct的對象放進去。。數組

    pair<string,int> p;函數

    pair<int ,int > p;spa

   pair<double,int> p;.net

  均可以。。。  對象

   應用:若是一個函數有兩個返回值 的話,若是是相同類型,就能夠用數組返回,若是是不一樣類型,就能夠本身寫個struct ,但爲了方便就能夠使用 c++  自帶的pair ,返回一個pair,其中帶有兩個值。除了返回值的應用,在一個對象有多個屬性的時候 ,通常本身寫一個struct ,若是就是兩個屬性的話,就能夠用pair 進行操做。。。blog

    應用pair 能夠省的本身寫一個struct 。。。若是有三個屬性的話,其實也是能夠用的pair 的 ,極端的寫法 pair <int ,pair<int ,int > >ip

寫法極端。(後邊的兩個 > > 要有空格,不然就會是 >>  位移運算符)get

makr_pair:string

   pair<int ,int >p (5,6);

   pair<int ,int > p1= make_pair(5,6);

   pair<string,double> p2 ("aa",5.0);

   pair <string ,double> p3 = make_pair("aa",5.0);

有這兩種寫法來生成一個pair。

 

 如何取得pair的值呢。。

 每一個pair 都有兩個屬性值  first  和second

 cout<<p1.first<<p1.second; 

 注意是屬性值而不是方法。

 

 

 

[cpp]  view plain  copy
 
  1. template <class T1, class T2> struct pair  
  2. {  
  3.   typedef T1 first_type;  
  4.   typedef T2 second_type;  
  5.   
  6.   T1 first;  
  7.   T2 second;  
  8.   pair() : first(T1()), second(T2()) {}  
  9.   pair(const T1& x, const T2& y) : first(x), second(y) {}  
  10.   template <class U, class V>  
  11.     pair (const pair<U,V> &p) : first(p.first), second(p.second) { }  
  12. }  

 

(補充:如下是網上搜的)

 

因爲pair類型的使用比較繁瑣,由於若是要定義多個形同的pair類型的時候,能夠時候typedef簡化聲明:

typedef pair<string, string> author;

author pro("May", "Lily");

author joye("James", "Joyce");

相關文章
相關標籤/搜索