Fast way to implement pop_front to a std::vector

前端 未结 4 731
遇见更好的自我
遇见更好的自我 2021-02-01 17:25

I\'m using some classes and several utility methods that use std:: vector.

Now I need to use each frame a pop_front - push_back method on one of those classes (but they

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 17:48

    I would expect:

    template
    void pop_front(std::vector& 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
    void pop_front(std::vector& 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.

提交回复
热议问题