【好记性不如烂笔头:在《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】

posted on 2012-09-05 23:14  cchun  阅读(344)  评论(0编辑  收藏  举报