Unfortunately std::map::operator[]
is a non-const member function, and you have a const reference.
You either need to change the signature of function
or do:
MAP::const_iterator pos = map.find("string");
if (pos == map.end()) {
//handle the error
} else {
std::string value = pos->second;
...
}
operator[]
handles the error by adding a default-constructed value to the map and returning a reference to it. This is no use when all you have is a const reference, so you will need to do something different.
You could ignore the possibility and write string value = map.find("string")->second;
, if your program logic somehow guarantees that "string"
is already a key. The obvious problem is that if you're wrong then you get undefined behavior.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…