【轉】c++ make_pair函數使用

【好記性不如爛筆頭:在《C++ Templates》看到這個函數,發現正是前段時間寫項目程序所要用到的,惋惜當時還不知道有這個用法,當時是本身寫了個結構體。。】
Utilities <utility> 
由短小精幹的類和函數構成,執行最通常性的工做。 
這些工具包括: 
general types 
一些重要的C函數 
numeric limits
html

Pairs 
C++標準程序庫中凡是「必須返回兩個值」的函數, 也都會利用pair對象 
class
ios

pair能夠將兩個值視爲一個單元。容器類別map和multimap就是使用pairs來管理其健值/實值(key/vaexpress

lue)的成對元素。 
pair被定義爲struct,所以可直接存取pair中的個別值.
函數

兩個pairs互相比較時, 第一個元素正具備較高的優先級. 
例: 
namespace std{ 
template <class T1, class T2> 
bool operator< (const pair<T1, T2>&x, const pair<T1, T2>&y){ 
return x.first<y.first || ((y.first<x.first)&&x.second<y.second); 

}
工具

make_pair():ui

無需寫出型別, 就能夠生成一個pair對象 
例: 
std::make_pair(42, '@'); 
而沒必要費力寫成: 
std::pair<int, char>(42, '@')
spa

當有必要對一個接受pair參數的函數傳遞兩個值時, make_pair()尤爲顯得方便, 
void f(std::pair<int, const char*>);
prototype

void foo{ 
f(std::make_pair(42, '@')); //pass two values as pair 
}
3d

1 pair的應用code

pair是將2個數據組合成一個數據,當須要這樣的需求時就可使用pair,如stl中的map就是將key和value放在一塊兒來保存。另外一個應用是,當一個函數須要返回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能夠接受隱式的類型轉換,這樣能夠得到更高的靈活度。靈活度也帶來了一些問題如:

std::pair<int, float>(1, 1.1);

std::make_pair(1, 1.1);

是不一樣的,第一個就是float,而第2個會本身匹配成double。

make_pair (STL Samples)

Illustrates how to use the make_pair Standard Template Library (STL) function in Visual C++.

 
template<class first, class second> inline
   pair<first,
      second> make_pair(
      const first& _X,
      const second& _Y
   )
NoteNote:

The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

The make_pair STL function creates a pair structure that contains two data elements of any type.

 
 
複製代碼
// 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;
}
18  3.14
10  1

Header: <utility>【內容摘自:http://hi.baidu.com/jrckkyy/blog/item/583c1bec1a44ca2e63d09f21.html】

相關文章
相關標籤/搜索