Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't vector::operator[] implemented similar to map::operator[]?

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;?

like image 241
1337ninja Avatar asked May 05 '16 02:05

1337ninja


1 Answers

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.

like image 112
jplatte Avatar answered Sep 20 '22 19:09

jplatte