-1

The square bracket operator in associative containers (map, unordered map) will insert an element in the map if it doesn't exist. In case the mapped value is an integer, like

std::map<std::string, int> map; // Or std::unordered_map

is calling the pre-increment operator well defined even in the case [] triggers the insertion of a new element?

I'm suspecting it should be ok, since in both ordered and unordered maps the standard mandates that a new element of type T is inserted as T() i.e. value initialization which means that the number zero is inserted.

Lorah Attkins
  • 5,331
  • 3
  • 29
  • 63
  • 2
    [yes](https://en.cppreference.com/w/cpp/container/map/operator_at). there is even exactly the same example there - `std::map word_map; ... ++word_map[w];` – dewaffled Dec 23 '21 at 17:35
  • @EOF Yes! Thanks for linking this – Lorah Attkins Dec 23 '21 at 17:50
  • There are also a good number of other duplicates, this is a common question about c++: https://stackoverflow.com/q/8943261/3185968 https://stackoverflow.com/q/62656874/3185968 – EOF Dec 23 '21 at 17:57

1 Answers1

-1

For the class template std::map and std::unordered_map the subscript operator returns a reference to an object of the mapped type

T& operator[](const key_type& x);

mapped_type& operator[](const key_type& k);

So the referenced object may be changed provided that the increment operator is defined for the mapped type.

The action of the operator is equivalent to

return try_emplace(k).first->second;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Isn't this the subscript operator of unordered map https://en.cppreference.com/w/cpp/container/unordered_map/operator_at ? – Lorah Attkins Dec 23 '21 at 17:42
  • 2
    @LorahAttkins I've never downvoted an answer that deserved the downvote more. – EOF Dec 23 '21 at 17:45
  • @LorahAttkins It is strange that in the C++ Standard the subscript operator for std::unordered_map is described at the end of the class definition while for std::map in the beginning of the class definition.:) So I have thought that it is absent for std::unoedered_map.:) – Vlad from Moscow Dec 23 '21 at 17:47