Is there a reason for the std :: vector [] operator to simply return a link instead of inserting a new element?
std::vector::operator[] is implemented as an array, since std::vector is a sequence container (that is, similar to an array). Standard arrays for integral types cannot be accessed outside boundaries. Similarly, access to std::vector::operator[] with an index outside the length of the vector is also not allowed. So yes, the reasons why it is not implemented, as you ask, because in a different context, arrays in C ++ do not work like that.
std::map::operator[] not a container of the sequence. Its syntax makes it look like associative arrays in other languages. As for C ++ (and its predecessor, C), map::operator[] is just syntactic sugar. This is the "black sheep" of the operator[] family, not std::vector::operator[] .
An interesting part of the C ++ specification is that accessing a map with a key that does not exist, using std::map::operator[] adds an element to the map. In this way,
#include <iostream>
leads to:
m['a'] == 1, m.size() == 1 m['b'] == 0, m.size() == 2
See also: Difference between map [] and map.at in C ++? :
[ map::at ] throws an exception if the key does not exist, find returns aMap.end() if the element does not exist, and the operator[] value initializes a new value for the corresponding key if the value does not exist.
source share