This is nothing new (except for me): when using the [] operator on a const map like
int get_number_map(const string& s, const map<string, int>& book)
{
return book[s];
}
you'll a compile-time error.
There are plenty of answers out there for the question "Why will my code not compile?", e.g. here. You should do return book.at(s);
(C++11 or later) or use the .find()
method.
Why is [] designed to work like this on maps? To me this is a side effect that breaks the consistency of the usage of [].