Moving a vector element to the back of the vector

后端 未结 3 857
闹比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

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

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

提交回复
热议问题