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);
}
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:Possibly the fastest way, would be to swap it with the last element
one operation! Ofcourse
std::swap
has to work withT
You can avoid the extra variable.
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.