Why there is no pop_front method in C++ std::vector?

Because a std::vector has no particular feature regarding inserting elements at the front, unlike some other containers. The functionality provided by each container makes sense for that container.

You probably should be using a std::deque, which is explicitly good at inserting at the front and back.

Check this diagram out.


Simple. Just try:

vec.erase(vec.begin());

vector is typically implemented something like this:

struct 
{
  T* begin; // points to the first T in the vector
  T* end; // points just after the last T in the vector
  int capacity; // how many Ts of memory were allocated
};

"begin" serves double-duty as "pointer to the first T in the vector" and "pointer to all the memory we allocated." therefore it's impossible to "pop" elements off the front of the vector by simply incrementing "begin" - do this and you no longer have a pointer to the memory you need to deallocate. that would leak memory. so a "pop_front" would need to copy all the Ts from the back of the vector to the front of the vector, and that is comparatively slow. so they decided to leave it out of the standard.

what you want is something like this:

struct 
{
  T* allocated; // points to all the memory we allocated
  T* begin; // points to the first T in the vector
  T* end; // points just after the last T in the vector
  int capacity; // how many Ts of memory were allocated
};

with this, you can "pop_front" by moving "begin" forward and backward with no danger of forgetting which memory to deallocate later. why doesn't std::vector work this way? i guess it was a matter of taste among those who wrote the standard. their goal was probably to provide the simplest possible "dynamically resizeable array" they could, and i think they succeeded.

Tags:

C++

Vector