【问题标题】:std::map access operator deprecated? no operator [] matches these operands不推荐使用 std::map 访问运算符?没有运算符 [] 匹配这些操作数
【发布时间】:2014-07-13 01:07:01
【问题描述】:

根据http://www.cplusplus.com/reference/map/map/,我可以使用m[k]m.at(k) 访问映射m 中键k 的值。但是,当我尝试这样做时

derivMap[fx]

在我的代码中,其中 derivMap 是 std::map<std::string,std::string> 类型的元素,Visual Studio 2013 给了我警告

没有运算符 [] 匹配这些操作数

但是,当我将代码更改为

derivMap.at(fx)

我没有错误。您对这个问题有任何见解吗?

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    map::operator[] 未被弃用。

    我猜你正试图在derivMapconst 的上下文中调用运算符。 map::operator[] 没有 const 重载,因为它可以通过在匹配键的元素不存在时插入元素来修改映射。另一方面,map::at() 确实有 const 重载,因为它被设计为在找不到元素时抛出。

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

    【讨论】:

    • 比起.at,我更喜欢.find。我从不使用.at
    • @MooingDuck 我想这取决于缺少元素是否是错误(以及您是否有 C++11。)
    • 在我的情况下,问题是 @juanchopanza 正确建议的 const 环境它也可以取决于方法签名,例如void SomeClass::foo() const{ int n = this-&gt;m[42] } 其中 m 是“SomeClass”类的字段。在这种情况下, const 导致了这种行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多