Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

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

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]

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...