Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::vector::push_front() exist? [duplicate]

Tags:

c++

vector

Since std::vector::push_back() exists, why doesn't std::vector::push_front() exist too?

I know there are others storage objects that work pretty much the same way and have an implementation of both push_back() and push_front() functions, but I was curious about the reason why std::vector doesn't.

like image 491
souki Avatar asked Jul 24 '18 13:07

souki


People also ask

Can std::vector have duplicates?

Yes, but sorting a vector modifies the original content.

Can vector have duplicates in C++?

The idea is to insert all vector elements in a set and copy the set's contents back again into the vector. This works as inserting elements into the set removes all duplicates as all set elements must be distinct. Please note that this might change the original ordering of elements in the vector.

Does vector have Push_front?

@Tyker: No. push_front has to move the existing objects, but it can move them in place by looping backwards.


2 Answers

You don't want to push_front on a vector ever. Adding an element to the front means moving every single other element in the vector one element back: O(n) copying. Terrible performance.

like image 83
72DFBF5B A0DF5BE9 Avatar answered Sep 20 '22 03:09

72DFBF5B A0DF5BE9


There's an important reason for that: std::vector<> is a continuous, single-ended array container. It allocates memory and starts writing the elements at the beginning of the allocated region. It usually allocates more memory than it needs to store all the current elements, so when you call push_back(), it writes the new element at the end and increments its element count. It's quick and efficient.

Push_front(), on the other hand, would require to somehow write the new element BEFORE all the current ones, at position [0] - however that's not trivial, since your array position [0] is occupied already. Push_front() would cause the whole array to be copied anew, so that its front can be modified. It would be an inefficient operation for which std::vector<> class is not designed.

You can still do it, of course, by calling

std::vector::insert(begin(), 1, val) 

But it'll cause the whole array to be copied just to add a single element.

like image 20
PlinyTheElder Avatar answered Sep 19 '22 03:09

PlinyTheElder