Screenplay: Why Not To Use operator[]
¶
Basic Operation (Looks Fine)¶
Insert two elements
#include <map> #include <iostream> int main() { std::map<int, std::string> my_map; my_map[1] = "one"; my_map[2] = "two"; std::cout << ':' << my_map[1] << ":\n"; std::cout << ':' << my_map[2] << ":\n"; return 0; }
Fine: they are in
$ ./cxx-stl-map-index-operator :one: :two:
And Elements That Have Never Been Inserted?¶
Now lets access an element that is not contained
#include <map> #include <iostream> int main() { std::map<int, std::string> my_map; std::cout << ':' << my_map[666] << ":\n"; return 0; }
It is in, but (apparently) with a default value
$ ./cxx-stl-map-index-operator-access-notexist ::
Know It: operator[]
Is Not Made For Read Access¶
Cannot use
operator[]
on aconst
map#include <map> #include <iostream> int main() { const std::map<int, std::string> my_map; std::cout << ':' << my_map[666] << ":\n"; return 0; }
map-index-operator-nonconst.cpp:7:35: error: passing ‘const std::map<int, std::__cxx11::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] 7 | std::cout << ':' << my_map[666] << ":\n"; | ^
If an element exists with key, a non-const reference to it is returned
If none exists, on is created ⟶ default constructed
⟶ May be overwritten