In addition to the excellent answer provided by @JanHerrmann, here is a general function for moving an element in a range:
#include <algorithm> #include <iostream> #include <iterator> // Moves the element src before dst, maintaining the order of other values template <typename RandomAccessIt> void moveElement(RandomAccessIt src, RandomAccessIt dst) { if (dst == src) { return; } if (dst < src) { std::rotate(dst, src, src + 1); } else { std::rotate(src, src + 1, dst); } } void printVector(const std::vector<int> &v) { std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; } int main() { std::vector<int> v = { 0, 1, 2, 3, 4, 5 }; printVector(v); // 0 1 2 3 4 5 moveElement(v.begin() + 4, v.begin()); printVector(v); // 4 0 1 2 3 5 moveElement(v.begin() + 2, v.begin() + 2); printVector(v); // 4 0 1 2 3 5 moveElement(v.begin() + 2, v.begin() + 3); printVector(v); // 4 0 1 2 3 5 moveElement(v.begin() + 2, v.end()); printVector(v); // 4 0 2 3 5 1 }
source share