Fast way to implement pop_front to a std::vector

前端 未结 4 733
遇见更好的自我
遇见更好的自我 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:37

    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.

    0 讨论(0)
  • 2021-02-01 17:48

    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.

    0 讨论(0)
  • 2021-02-01 17:48

    if you just try to erase the first element then in the function use:

    if (my_vector.size()){ //check if there any elements in the vector array
        my_vector.erase(my_vector.begin()); //erase the firs element
    }
    

    if you want to emulate pop front for the entire vector array ( you want to keep pop out every element from start to end) , i suggest on:

    reverse(my_vector.begin(),my_vector.end());  // reverse the order of the vector array
    my_vector.pop_back();   // now just simple pop_back will give you the results
    
    0 讨论(0)
  • 2021-02-01 17:51

    I also have a way... Not so good tho..

    This looks like @0xPwn's solution, but he didn't reverse the vector the second time. You will probably understand this code, so i will not explain it.

    #include <algorithm>
    #include <vector>
    template <typename T>
    void pop_front(std::vector<T>& vec){
        std::reverse(vec.begin(),vec.end()); // first becomes last, reverses the vector
        vec.pop_back(); // pop last
        std::reverse(vec.begin(),vec.end()); // reverses it again, so the elements are in the same order as before
    
    }
    
    0 讨论(0)
提交回复
热议问题