The insert
and erase
are iterators, not indexes:
ObjectToRotate.insert(ObjectToRotate.begin(), ObjectToRotate.back()); ObjectToRotate.pop_back(); // or erase(ObjectToRotate.end()-1), if you prefer
But it may be more efficient to remove the last item (after copying) to avoid the possibility of redistribution:
auto back = ObjectToRotate.back(); ObjectToRotate.pop_back(); ObjectToRotate.insert(ObjectToRotate.begin(), back);
or use std::rotate
:
std::rotate(ObjectToRotate.begin(), ObjectToRotate.end()-1, ObjectToRotate.end());
If you do this a lot, then deque
may be the best container choice, as it allows you to efficiently insert and remove from both ends. But, if speed is important, make sure you measure and verify that it is truly an improvement; if the sequence is not very long, then the overhead from a more complex memory layout can make deque
slower.
source share