c++ pair make_pair 数据对

28 篇文章 4 订阅

std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。例如std::pair

template pair make_pair(T1 a, T2 b) { return pair(a, b); }

头文件

#include<utility>

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类型。这个问题在编程是需要引起注意。

实例

#include <iostream>
#include <utility>
#include <string>
usingnamespace std;

int main () {
pair <string,double> product1 ("tomatoes",3.25);
pair <string,double> product2;
pair <string,double> product3;

product2.first ="lightbulbs"; // type of first is string
product2.second =0.99; // type of second is double

product3 = make_pair ("shoes",20.0);

cout <<"The price of "<< product1.first <<" is $"<< product1.second <<"\n";
cout <<"The price of "<< product2.first <<" is $"<< product2.second <<"\n";
cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n";
return0;
}

其运行结果如下:

The price of tomatoes is $3.25
The price of lightbulbs is $0.99
The price of shoes is $20

make_pair用于构建一个pair

 pair make_pair(T1 x, T2 y)
 {
     return pair(x, y);
 }
std::pair("sn001", 12.5);
std::make_pair("sn001", 12.5);
 两者效果一样。

使用:

std::pair m_pairA;
m_pairA = std::make_pair("sn001", 12.5);
std::cout<<m_pairA.first<<"  "<<m_pairA.second<<std::endl;

结合map的简单使用:

std::pair m_pairA;
m_pairA = std::make_pair("sn001", 12.5);
std::cout<<m_pairA.first<<"  "<<m_pairA.second<<std::endl;
std::map m_mapA;
m_mapA.insert(m_pairA);
std::map::iterator iter = m_mapA.begin();
std::cout<<iter->first<<"  "<<iter->second<<std::endl;
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值