Fast way to implement pop_front to a std::vector

I would expect:

template<typename T>
void pop_front(std::vector<T>& vec)
{
    assert(!vec.empty());
    vec.front() = std::move(vec.back());
    vec.pop_back();
}

to be the most efficient way of doing this, but it does not maintain the order of the elements in the vector.

If you need to maintain the order of the remaining elements in vec, you can do:

template<typename T>
void pop_front(std::vector<T>& vec)
{
    assert(!vec.empty());
    vec.erase(vec.begin());
}

This will have linear time in the number of elements in vec, but it is the best you can do without changing your data structure.

Neither of these functions will maintain the vector at a constant size, because a pop_front operation will by definition remove an element from a container.

Leave a Comment