1

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 [].

jake77
  • 1,892
  • 2
  • 15
  • 22
  • 2
    Because if it wasn't, you would need an additional check each time you use it and you actually want to insert something. – Michael Chourdakis Apr 20 '20 at 20:19
  • 4
    `[]` returns a reference to the item being indexed, so the item must exist. Therefore in the case of a map the item has to be created if it doesn't already exist. – john Apr 20 '20 at 20:21
  • @MichaelChourdakis and if I only want to print the value of an existing key? Or as in this case, return the value? Why can't I read an immutable object? – jake77 Apr 20 '20 at 20:48
  • @jake77 You can, using `at` or `find`. It may not be the syntax you want, but it's what the standards committee decided was best given other design choices in the language. The argument for using specifically `operator []` for read-only indexing into a const map is not terribly strong, beyond a weak argument for convenient notation. – nanofarad Apr 20 '20 at 21:17
  • 1
    @nanofarad As you may have guessed I'm quite new to C++. I have a python background and frankly, such inconsistency is for me something new. – jake77 Apr 20 '20 at 21:24

0 Answers0