C++之pair與make_pair

  • 現實動機

http://blog.csdn.net/sprintfwater/article/details/8765034

1、pair
應用1:pair是將2個數據組合成一個數據,當有這樣的需求時就可以使用pair,如stl中的map就是將key和value放在一起來保存。
應用2:當一個函數需要返回2個數據的時候,可以選擇pair。 pair的實現是一個結構體,主要的兩個成員變量是first second 因爲是使用struct不是class,所以可以直接使用pair的成員變量。

2、make_pair函數

template pair make_pair(T1 a, T2 b) { 
    return pair(a, b); 
}

很明顯,我們可以使用pair的構造函數也可以使用make_pair來生成我們需要的pair。 一般make_pair都使用在需要pair做參數的位置,可以直接調用make_pair生成pair對象很方便,代碼也很清晰。 另一個使用的方面就是pair可以接受隱式的類型轉換,這樣可以獲得更高的靈活度。

  • 實例-1

http://www.cplusplus.com/reference/utility/make_pair/

// make_pair example
#include <utility>      // std::pair
#include <iostream>     // std::cout

int main () {
  std::pair <int,int> foo;
  std::pair <int,int> bar;

  foo = std::make_pair (10,20);
  bar = std::make_pair (10.5,'A'); // ok: implicit conversion from pair<double,char>

  std::cout << "foo: " << foo.first << ", " << foo.second << '\n';
  std::cout << "bar: " << bar.first << ", " << bar.second << '\n';

  return 0;
}

Output:

foo: 10, 20
bar: 10, 65

  • 實例-2

http://blog.csdn.net/yockie/article/details/6980692

// mkpair.cpp
// compile with: /EHsc
// Illustrates how to use the make_pair function.
//
// Functions: make_pair - creates an object pair containing two data
//                        elements of any type.

#include <utility>
#include <iostream>

using namespace std;

/* STL pair data type containing int and float
*/

typedef struct pair<int,float> PAIR_IF;

int main(void)
{
  PAIR_IF pair1=make_pair(18,3.14f);

  cout << pair1.first << "  " << pair1.second << endl;
  pair1.first=10;
  pair1.second=1.0f;
  cout << pair1.first << "  " << pair1.second << endl;
}
/****
Output
18  3.14
10  1
****/
  • 抽象定義
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章