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.
Yes, but sorting a vector modifies the original content.
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.
@Tyker: No. push_front has to move the existing objects, but it can move them in place by looping backwards.
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.
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.
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