How to use the rotate() function in C++?

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.

Parameters

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.

Return

The rotate() function does not return any values.

Code

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;
}

Explanation:

  • From lines 1 to 3, we import the required header files.
  • In line 7, we create a vector containing integer values.
  • From lines 8 to 10, we print the values of the vector before performing a rotation.
  • In line 14, we call the 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.
  • Finally, from lines 15 to 17, we print the rotated vector.

So, in this way, we can perform the rotation of elements efficiently in C++.