std :: map存取操作符已弃用?没有operator []匹配这些操作数 [英] std::map access operator deprecated? no operator [] matches these operands

查看:171
本文介绍了std :: map存取操作符已弃用?没有operator []匹配这些操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://www.cplusplus.com/reference/map/map/ ,我可以使用 m [k] m.at(k)地图中的键 k m 。但是,当我尝试做

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 m. However, when I try to do

derivMap[fx]

在我的代码中,其中derivMap是 std :: map Visual Studio 2013给我警告

in my code, where derivMap is an element of type std::map<std::string,std::string> Visual Studio 2013 gives me the warning


无操作符[]匹配这些操作数

no operator [] matches these operands

但是,当我将代码更改为

However, when I change my code to

derivMap.at(fx)

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

I get no error. Do you have any insight into this issue?

推荐答案

map :: operator [] 不会弃用。

map::operator[] is not deprecated.

我猜想你在 derivMap const 的上下文中尝试调用运算符。 map :: operator [] 没有 const 重载,因为它可以通过插入元素来修改地图一个匹配的键不存在。 map :: at()另一方面,有一个 const 重载,因为它被设计为当元素。

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<int, int>& m)
{
  int n = m[42]; // OK
}

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

这篇关于std :: map存取操作符已弃用?没有operator []匹配这些操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆