【轉】c++ make_pair函數使用


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

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

pair可以將兩個值視為一個單元。容器類別map和multimap就是使用pairs來管理其健值/實值(key/va

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():

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

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

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

1 pair的應用

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】


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM