C++中的pair,make_pair学习

原文地址:https://blog.csdn.net/bingqingsuimeng/article/details/73480190

std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。例如std::pair<int,float>或者std::pair<double,double>等。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>

4usingnamespace std;

5

6int main () {

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

8pair<string,double>product2;

9pair<string,double>product3;

10

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

12product2.second =0.99; // type of second isdouble

13

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

15

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

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

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

19return0;

20}

其运行结果如下:

1The price of tomatoes is$3.25

2The price of lightbulbs is$0.99

3The price of shoes is $20

01 pair  vs make_pair

02 make_pair constructs a pairobject.

03 template

04 pair make_pair(T1 x, T2y)

05 {

06     returnpair(x, y);

07 }

08

09 eg:  std::pair("sn001",12.5);

10       std::make_pair("sn001",12.5);

11       两者效果一样。

12 倘若:std::pair("sn002", 12.6);  // 12.6's datatype is float

13        std::make_pair("sn002",12.6); // 12.6's datatype is double

14 使用:

15        std::pairm_pairA;

16        m_pairA =std::make_pair("sn001", 12.5);

17       std::cout<<m_pairA.first<<" "<<m_pairA.second<<std::endl;

18 结合map的简单使用:

19        std::pairm_pairA;

20        m_pairA =std::make_pair("sn001", 12.5);

21       //std::cout<<m_pairA.first<<" "<<m_pairA.second<<std::endl;

22        std::mapm_mapA;

23       m_mapA.insert(m_pairA);

24        std::map::iterator iter =m_mapA.begin();

25       std::cout<<iter->first<<" "<<iter->second<<std::endl;

小结:

  make_pair创建的是一个pair对象。使用都很方便,针对成对出现的数据,如书的ISBN对应一个书名。

  pair是单个数据对的操作,pair是一struct类型,有两个成员变量,通过first,second来访问,用的是“.”访问。

  map是一个关联容器,里面存放的是键值对,容器中每一元素都是pair类型,通过map的insert()方法来插入元素(pair类型)。

猜你喜欢

转载自blog.csdn.net/lv0918_qian/article/details/81772735