Moving a vector element to the back of the vector

后端 未结 3 855
闹比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: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 
    void moveItemToBack(std::vector& v, size_t itemIndex)
    {
        auto it = v.begin() + itemIndex;
        std::rotate(it, it + 1, v.end());
    }
    

提交回复
热议问题