c++ shift elements in vector code example
Example 1: c++ shift array to the right
const int SIZE = 9;
int arr[SIZE]={1,2,3,4,5,6,7,8,9};
int last = arr[SIZE - 1];
for (int i = SIZE - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = last;
Example 2: shift element to end of vector c++
template <typename t> void move(std::vector<t>& v, size_t oldIndex, size_t newIndex)
{
if (oldIndex > newIndex)
std::rotate(v.rend() - oldIndex - 1, v.rend() - oldIndex, v.rend() - newIndex);
else
std::rotate(v.begin() + oldIndex, v.begin() + oldIndex + 1, v.begin() + newIndex + 1);
}
auto initial_pos = 1;
auto final_pos = 4;
move(some_vector, initial_pos, final_pos);