std::map access operator deprecated? no operator [] matches these operands

后端 未结 1 686
我在风中等你
我在风中等你 2020-12-18 21:26

According to http://www.cplusplus.com/reference/map/map/, I can use either m[k] or m.at(k) to access the value of a key k in a map

1条回答
  •  天涯浪人
    2020-12-18 22:04

    map::operator[] is not deprecated.

    I will guess that you are attempting to call the operator in a context where derivMap is const. map::operator[] does not have a const overload, because it can modify the map by inserting an element when one matching the key isn't present. map::at() on the other hand, does have a const overload because it is designed to throw when an element is not found.

    void foo(std::map& m)
    {
      int n = m[42]; // OK
    }
    
    void bar(const std::map& m)
    {
      int n = m[42]; // ERROR
    }
    

    0 讨论(0)
提交回复
热议问题