Moving a vector element to the back of the vector

2020-07-05 05:55发布

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 <typename T>
void moveItemToBack(std::vector<T>& v, size_t itemIndex)
{
   T tmp(v[itemIndex]);
   v.erase(v.begin() + itemIndex);
   v.push_back(tmp);
}

3条回答
相关推荐>>
2楼-- · 2020-07-05 06:30

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());
}
查看更多
贼婆χ
3楼-- · 2020-07-05 06:33

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

查看更多
做个烂人
4楼-- · 2020-07-05 06:35

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.

查看更多
登录 后发表回答