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't move elements from one vector to another the way you are thinking about; you will always have to erase the element positions from the first vector. If you want to change all the elements from the first vector into the second and vice versa you can use swap.
push_front() function is used to push elements into a list from the front. The new value is inserted into the list at the beginning, before the current first element and the container size is increased by 1.
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()); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With