如何在C++中将浮点值插入到地图中

How to insert float values in to a map in C++?

本文关键字:插入 地图 C++      更新时间:2023-10-16

我需要在 std::map<int,std::pair<float,float> > 类型的映射中插入 3 个值。这样地图的数据将作为 { 22 32626.23 53232.63 }

std::map<int,std::pair<float,float> > my_MainMap;
std::map<float,float>  myMap1;
int iValue;
float fValue1, fValue2;       

我尝试了 3 种不同的插入值的方法:方法一:

myMap1.insert(std::pair<float, float>(fValue1, fValue2));
m_Mainmap.insert(std::pair<int,std::pair<float,float> >(iValue,myMap1 ));

方法2:

m_Mainmap.insert(std::pair<int,std::pair<float,float>>::value_type(iValue,fValue1, fValue2));

方法3:

myMap1.insert(std::pair<float, float>(fValue1, fValue2));
m_Mainmap.insert(std::make_pair(iValue,myMap1 ));

我编写的代码没有编译。我错在哪里?

In constructor 'std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = int, _U2 = std::map<float, float>, _T1 = const int, _T2 = std::pair<float, float>]':
 error: no matching function for call to 'std::pair<float, float>::pair(const std::map<float, float>&)'

方法 2 几乎就在那里。您需要考虑已嵌套一对的事实。

m_Mainmap.insert(std::pair<int, std::pair<float,float>>(i, std::pair<float,float>(fOuterRadius,fInnerRadius)));

m_Mainmap.insert(std::make_pair(i, std::make_pair(fOuterRadius,fInnerRadius)));

只要您知道插入函数和此运算符之间的区别,还请考虑以下几点。(如果键已存在,则插入不会更新值)

m_Mainmap[i] = std::pair<float,float>(fOuterRadius,fInnerRadius);

我不知道你的std::map<float,float>是干什么用的,因为你从来没有在你的问题陈述中详细说明它。