Is there any reason for std::vector's operator[] to just return a reference instead of inserting a new element?
std::vector::operator[]
is implemented in an array-like fashion because std::vector
is a sequence container (i.e., array-like). Standard arrays for integral types cannot be accessed out of bounds. Similarly, accessing std::vector::operator[]
with an index outside of the vector's length is not allowed either. So, yes, the reasons it is not implemented as you ask about is because in no other context, do arrays in C++ act like that.
std::map::operator[]
is not a sequence container. Its syntax makes it similar to associative arrays in other languages. In terms of C++ (and its predecessor, C), map::operator[]
is just syntactic sugar. It is the "black sheep" of the operator[]
family, not std::vector::operator[]
.
The interesting part of the C++ specification regarding is that accessing a map with a key that doesn't exist, using std::map::operator[]
, adds an element to the map. Thus,
#include <iostream>
#include <map>
int main(void) {
std::map<char, int> m;
m['a'] = 1;
std::cout << "m['a'] == " << m['a'] << ", m.size() == " << m.size() << std::endl;
std::cout << "m['b'] == " << m['b'] << ", m.size() == " << m.size() << std::endl;
}
results in:
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 doesn't exist, find
returns aMap.end()
if the element doesn't exist, and operator[]
value-initializes a new value for the corresponding key if no value exists there.