地图问题

时间:2016-07-29 17:33:36

标签: c++ c++11 dictionary

我确实有以下结构定义

struct WayStruct{
    double ID;
    string Neighbours;
};

以及地图

map <double,WayStruct> WayMap;

要向此地图添加新元素,请使用

WaysFind.ID=999;
WaysFind.Neighbours="test";
WayMap.insert(1234,WaysFind);

但是我无法编译。 Dev-C ++与

错误结束
[Error] no matching function for call to 'std::map<double, WayStruct>::insert(double, WayStruct&)' 

有人能说出我在这里做错了吗?

当我使用make_pair Dev-C ++时返回

   In instantiation of 'std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = double; _U2 = int; _T1 = const char; _T2 = WayStruct]': 
     required from here 
111 39 c:\program files (x86)\dev-cpp\mingw64\lib\gcc\x86_64-w64-mingw32\4.7.1\include\c++\bits\stl_pair.h [Error] no matching function for call to 'WayStruct::WayStruct(const int&)' 

在文件stl_pair.h中

2 个答案:

答案 0 :(得分:5)

您尝试使用的

std::map::insert()重载接受一个std::map:value_type类型的参数,即std::pair而不是两个参数。为map插入值的常见方法是:

WayMap.insert( std::make_pair( 1234,WaysFind ) );

对于C ++ 11,您可以插入尝试使用emplace代替的方式:

WayMap.emplace( 1234, WaysFind );

另外注意,您应该注意使用double作为密钥的可能问题。

答案 1 :(得分:1)

您必须按如下方式使用:

WayMap.insert(std::pair<double,WayStruct>(1234,WaysFind));

演示:http://coliru.stacked-crooked.com/a/df5e4413eceb68be

如果你有C ++ 11或更高版本的兼容编译器,这也可以工作:

WayMap.insert(std::make_pair(1234,WaysFind));
相关问题