C++ std::pair 与 std::make_pair

std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。例如std::pair 或者 std::pair等。pair实质上是一个结构体,其主要的两个成员变量是first和second,这两个变量可以直接使用。初始化一个pair可以使用构造函数,也可以使用std::make_pair函数,make_pair函数的定义如下:
template pair make_pair(T1 a, T2 b) {returnpair(a, b); }

一般make_pair都使用在需要pair做参数的位置,可以直接调用make_pair生成pair对象。 另一个使用的方面就是pair可以接受隐式的类型转换,这样可以获得更高的灵活度。但是这样会出现如下问题:例如有如下两个定义:

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



std::make_pair(
1,1.1);


其中第一个的second变量是float类型,而make_pair函数会将second变量都转换成double类型。这个问题在编程是需要引起注意。下面是一段pair与make_pair的例子程序:


1#include<iostream>

2#include<utility>

3#include<string>

4usingnamespacestd;

5

6intmain () {

7pair<string,double>product1 ("tomatoes",3.25);

8pair<string,double>product2;

9pair<string,double>product3;

10

11product2.first="lightbulbs";//type of first is string

12product2.second=0.99;//type of second is double

13

14product3=make_pair ("shoes",20.0);

15

16cout<<"The price of"<<product1.first<<"is $"<<product1.second<<"\n";

17cout<<"The price of"<<product2.first<<"is $"<<product2.second<<"\n";

18cout<<"The price of"<<product3.first<<"is $"<<product3.second<<"\n";

19return0;

20}
其运行结果如下:


1The price of tomatoesis$3.25

2The price of lightbulbsis$0.99

3The price of shoesis$20
为了更好的了解pair与make_pair的机制,下面是其定义:
1//TEMPLATE STRUCT pair

2template<class_Ty1,class_Ty2>structpair

3{//store a pair of values

4typedef pair<_Ty1, _Ty2>_Myt;

5typedef _Ty1 first_type;

6typedef _Ty2 second_type;

7

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

9{//construct from defaults

10}

11

12pair(const_Ty1&_Val1,const_Ty2&_Val2): first(_Val1), second(_Val2)

13{//construct from specified values

14}

15

16template<class_Other1,

17class_Other2>

18pair(constpair<_Other1, _Other2>&_Right)

19: first(_Right.first), second(_Right.second)

20{//construct from compatible pair

21}

22

23voidswap(_Myt&_Right)

24{//exchange contents with _Right

25std::swap(first, _Right.first);

26std::swap(second, _Right.second);

27}

28

29_Ty1 first;//the first stored value

30_Ty2 second;//the second stored value

31};

32

33

34template<class_Ty1,class_Ty2>inline

35pair<_Ty1, _Ty2>make_pair(_Ty1 _Val1, _Ty2 _Val2)

36{//return pair composed from arguments

37return(pair<_Ty1, _Ty2>(_Val1, _Val2));

38}


原文链接: https://www.cnblogs.com/Nimeux/archive/2010/10/05/1844191.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/15757

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午3:47
下一篇 2023年2月7日 下午3:49

相关推荐