Moving a vector element to the back of the vector

后端 未结 3 856
闹比i
闹比i 2021-02-12 14:45

Is there any better way (either faster or with fewer symbols of code) than erasing the element and re-adding it to the back?

template 
void mov         


        
相关标签:
3条回答
  • 2021-02-12 15:18

    You can avoid the extra variable.

    v.push_back(v[itemIndex]);
    v.erase(v.begin() + itemIndex);
    

    If you delete frequently from the middle of the vector and can rewrite your code so that it doesn't require random access, you may be able to improve efficiency by using a linked list (std::list) instead.

    0 讨论(0)
  • 2021-02-12 15:22

    You can do this with std::rotate from the standard library. Since this doesn't change the vector size it also won't trigger a reallocation. Your function would look something like this:

    template <typename T>
    void moveItemToBack(std::vector<T>& v, size_t itemIndex)
    {
        auto it = v.begin() + itemIndex;
        std::rotate(it, it + 1, v.end());
    }
    
    0 讨论(0)
  • 2021-02-12 15:22

    Possibly the fastest way, would be to swap it with the last element

    template <typename T>
    void moveItemToBack(std::vector<T>& v, size_t itemIndex)
    {
       std::swap(v[itemIndex], v.back()); // or swap with *(v.end()-1)
    }
    

    one operation! Ofcourse std::swap has to work with T

    0 讨论(0)
提交回复
热议问题