Is there any reason for std::vector
's operator[]
to just return a reference instead of inserting a new element? The cppreference.com page for vector::operator
says here
Unlike
std::map::operator[]
, this operator never inserts a new element into the container.
While the page for map::operator[]
says
"Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist."
Why couldn't vector::operator[]
be implemented by calling vector::push_back
or vector::insert
like how map::operator[]
calls insert(std::make_pair(key, T())).first->second;
?
Quite simply: Because it doesn't make sense. What do you expect
std::vector<int> a = {1, 2, 3};
a[10] = 4;
to do? Create a fourth element even though you specified index 10? Create elements 3 through to 10 and return a reference to the last one? Neither would be particularily intuitive.
If you really want to fill a vector with values using operator[]
instead of push_back
, you can call resize
on the vector to create the elements before settings them.
Edit: Or, if you actually want to have an associative container, where the index is important apart from ordering, std::map<int, YourData>
might actually make more sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With