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.


Since pop_front() only erases the first element, the direct implementation is this:

template <typename V>
void pop_front(V & v)
{
    assert(!v.empty());
    v.erase(v.begin());
}

Don't worry about speed for now. If you want to go back and optimize code, ask for dedicated project time.