The rotate()
function in C++ is used to rotate the elements’ order within a specified range. This is done in such a way that the element pointed by middle
now becomes the first element. In other words, the rotation happens at the iterator, pointing to the middle
element.
Here,
middle
does not mean the middlemost element in an array. It means any elements present within the range at which we want to rotate the elements. In other words, it is the element at which you want to rotate the elements present in the array or vector.
This function is available in the <algorithm.h>
header file.
The rotate()
function accepts the following parameters:
first
: An iterator that points to the array’s first index or vector from where we want to rotate the elements.
middle
: An iterator that points to the element of the array or vector at which the rotation will be performed. This element now comes at the start of the array.
last
: This is an iterator that points to the last index of the array or vector until where we want to rotate the elements.
The rotate()
function does not return any values.
Let’s look at the code now to understand it better.
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main() {vector<int> vec = {1,2,3,4,5,6,7,8,9};cout << "Original vector: ";for (int x: vec)cout << x << " ";cout << endl;rotate(vec.begin(), vec.begin() + 3, vec.end());cout << "Rotated vector: ";for (int x: vec)cout << x << " ";return 0;}
rotate()
function and pass the required parameters. We can see that we specified that we want to rotate the elements in the vector at index 3.So, in this way, we can perform the rotation of elements efficiently in C++.