Moving a vector element to the back of the vector

Violet Giraffe picture Violet Giraffe · May 21, 2014 · Viewed 23.1k times · Source

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);
}

Answer

Blastfurnace picture Blastfurnace · May 21, 2014

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());
}