C ++ unordered_map :: insert无法编译

Use*_*erX -2 c++ stl unordered-map insert

我只需要从一个浮动对象到另一个浮动对象的哈希图。应该很简单,不是吗?编译器只是不接受它:

宣言:

unordered_map<float, float> m_mffPhotoPeakMap;
Run Code Online (Sandbox Code Playgroud)

使用:

float CProductSpecs::AddToMap(float fEnergy, float returnedValue) const
{
    auto pair = make_pair(fEnergy, returnedValue);
    m_mffPhotoPeakMap.insert(pair);                 // Error!  (First attempt)
    m_mffPhotoPeakMap[fEnergy] = returnedValue;     // Error!  (Second attempt)
    return returnedValue;
}
Run Code Online (Sandbox Code Playgroud)

错误消息(第一次尝试):

Severity    Code    Description Project File    Line    Suppression State
Error   C2663   'std::_Hash<std::_Umap_traits<_Kty,_Ty,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>::insert': 6 overloads have no legal conversion for 'this' pointer
Run Code Online (Sandbox Code Playgroud)

错误消息(第二次尝试):

Severity    Code    Description Project File    Line    Suppression State
Error   C2678   binary '[': no operator found which takes a left-hand operand of type 'const std::unordered_map<float,float,std::hash<float>,std::equal_to<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)     
Run Code Online (Sandbox Code Playgroud)

错误消息对我来说没有意义-语法似乎正确。谁能告诉我我在做什么错?

jwe*_*rek 8

您正在const尝试更改成员变量的成员函数。

使CProductSpecs :: AddToMap不为const

  • @UserX AddToMap()为const是没有意义的。听起来您的代码具有更广泛的const正确性问题。 (3认同)
  • @UserX从技术上讲,`const_cast`可以帮助您避免编译错误,但是有可能在代码中引起未定义的行为,因此是“不要”的部分。 (2认同)