轉:C++ pair用法
摘自:
http://hi.baidu.com/lucene1983/blog/item/83bb68351d12ffbed1a2d3fe.html1 pair的應用
pair是將2個數(shù)據(jù)組合成一個數(shù)據(jù),當需要這樣的需求時就可以使用pair,如stl中的map就是將key和value放在一起來保存。另一個應用是,當一個函數(shù)需要返回2個數(shù)據(jù)的時候,可以選擇pair。 pair的實現(xiàn)是一個結構體,主要的兩個成員變量是first second 因為是使用struct不是class,所以可以直接使用pair的成員變量。
2 make_pair函數(shù)
template pair make_pair(T1 a, T2 b) { return pair(a, b); }
很明顯,我們可以使用pair的構造函數(shù)也可以使用make_pair來生成我們需要的pair。 一般make_pair都使用在需要pair做參數(shù)的位置,可以直接調用make_pair生成pair對象很方便,代碼也很清晰。 另一個使用的方面就是pair可以接受隱式的類型轉換,這樣可以獲得更高的靈活度。靈活度也帶來了一些問題如:
std::pair<int, float>(1, 1.1);
std::make_pair(1, 1.1);
是不同的,第一個就是float,而第2個會自己匹配成double。
以上是從網(wǎng)上找來的資料,我又查了一下關于pair的定義,其定義是一個模板結構。
// TEMPLATE STRUCT pair
template<class _Ty1,
class _Ty2> struct pair

{ // store a pair of values
typedef pair<_Ty1, _Ty2> _Myt;
typedef _Ty1 first_type;
typedef _Ty2 second_type;

pair()
: first(_Ty1()), second(_Ty2())

{ // construct from defaults
}

pair(const _Ty1& _Val1, const _Ty2& _Val2)
: first(_Val1), second(_Val2)

{ // construct from specified values
}

template<class _Other1,
class _Other2>
pair(const pair<_Other1, _Other2>& _Right)
: first(_Right.first), second(_Right.second)

{ // construct from compatible pair
}

void swap(_Myt& _Right)

{ // exchange contents with _Right
std::swap(first, _Right.first);
std::swap(second, _Right.second);
}

_Ty1 first; // the first stored value
_Ty2 second; // the second stored value
};
make_pair同樣也是一個模板函數(shù)。其定義如下:
template<class _Ty1,
class _Ty2> inline
pair<_Ty1, _Ty2> make_pair(_Ty1 _Val1, _Ty2 _Val2)

{ // return pair composed from arguments
return (pair<_Ty1, _Ty2>(_Val1, _Val2));
}
posted on 2009-10-15 11:09
Sandy 閱讀(12046)
評論(0) 編輯 收藏 引用 所屬分類:
c++學習