Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why not implement c++ std::vector::pop_front() by shifting the pointer to vector[0]?

Why can't pop_front() be implemented for C++ vectors by simply shifting the pointer contained in the vector's name one spot over? So in a vector containing an array foo, foo is a pointer to foo[0], so pop_front() would make the pointer foo = foo[1] and the bracket operator would just do the normal pointer math. Is this something to do with how C++ keeps track of the memory you're using for what when it allocates space for an array?

This is similar to other questions I've seen about why std::vector doesn't have a pop_front() function, I will admit, but i haven't anyone asking about why you can't shift the pointer.

like image 347
Ian Ooi Avatar asked Jan 31 '12 05:01

Ian Ooi


People also ask

Is there Pop_front in vector C++?

Implement pop_front operation for a vector in C++ Both operations run in constant time. The pop_front operation will take at-least O(n) time since the vector is backed by an array and all the remaining elements need to be shifted by one position to the left to preserve the order.

What does std::vector do?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

Is vector guaranteed to be contiguous?

Yes, the elements of a std::vector are guaranteed to be contiguous.

Is vector implemented as array?

Vector is a linear data structure that stores similar type objects. It is a template class in C++ STL(standard template library). A vector is implemented as an array which is free to add elements even beyond its predefined size.


1 Answers

I started typing out an elaborate answer explaining how the memory is allocated and freed but after typing it all out I realized that memory issues alone don't justify why pop_front isn't there as other answers here suggested.

Having pop_front in a vector where the extra cost is another pointer is justifiable in most circumstances. The problem, in my opinion, is push_front. If the container has pop_front then it should also have push_front otherwise the container is not being consistent. push_front is definitely expensive for a vector container (unless you match your pushes with your pops which is not a good design). Without push_front the vector is really wasting memory if one does lots of pop_front operations with no push_front functionality.

Now the need for pop_front and push_front is there for a container that is similar to a vector (constant time random access) which is why there is deque.

like image 64
Samaursa Avatar answered Sep 24 '22 20:09

Samaursa