A linked list would be a good approach since you don't need to move all the intermediate elements around. std::list
works just fine, combined with splice()
. You will need an iterator to the element you want to move to the front:
#include <list>
#include <iostream>
#include "prettyprint.hpp"
int main()
{
std::list<int> x { 1, 4, 6, 7, 2 };
auto i = x.begin(); std::advance(i, 2); // i points to 6
std::cout << x << std::endl; // [1, 4, 6, 7, 2]
x.splice(x.begin(), x, i);
std::cout << x << std::endl; // [6, 1, 4, 7, 2]
}
(Using the pretty printer for a quick demo.)
As others have said, whether that's more efficient that a random-access container depends on how you are tracking the element that you want to move.
Update: In light of Steve's remarks I should like to offer a raw C-array solution, too. It has the benefit that you can access it by position in O(1) time and that it requires minimum space:
char y[] = { 'a', 'c', 'Q', '%', '5' };
std::cout << pretty_print_array(y) << std::endl; // [a, c, Q, %, 5]
std::rotate(y, y + 2, y + sizeof(y));
std::cout << pretty_print_array(y) << std::endl; // [Q, %, 5, a, c]
The rotate
call could be wrapped in a function:
template <typename T, size_t N>
void bring_forward(T (& a)[N], size_t p) { std::rotate(a, a + p, a + N); }