Rotates the order of the elements

You're viewing an older version of this page (#4153). View the current version.

View versions (1)

Definition

The rotate() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator >
   void rotate(
      ForwardIterator first, 
      ForwardIterator middle, 
      ForwardIterator last
   );

Parameters

ParameterDescription
firstA forward iterator addressing the position of the first element in the range to be rotated
middleA forward iterator defining the boundary within the range that addresses the position of the first element in the second part of the range whose elements are to be exchanged with those in the first part of the range
lastA forward iterator addressing the position one past the final element in the range to be rotated

Description

Rotate function rotates a sequence. It means the sequence will start at the element in the middle of the source sequence and the last element will be followed by the first (it appends the element between the first and the middle element to the elements between the middle and the last element).

Return Value

None.

Complexity

The complexity is linear; performs at most last - first swaps.

References

Example 1
Problem

This program illustrates the use of the STL rotate() algorithm to rotate the order of all, or just some, of the values in a vector of integers.

Workings
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
  int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  vector<int> v(a, a+10);

  cout <<"\nHere are the contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  cout <<"\nNow we rotate the order of all values in the vector "
         "\nin so that the fourth value becomes the first value.";
  
  rotate(v.begin(), v.begin()+3, v.end());
  
  cout <<"\nHere are the revised contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  cout <<"\nNext we rotate the order of the 2nd to the 6th values "
         "in the vector so that\nthe third value in that group of values "
         "becomes the first value of the group.";

  rotate(v.begin()+1, v.begin()+3, v.begin()+6);

  cout <<"\nHere are the revised contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  return 0;
}
Solution

Output:

Here are the contents of the vector:
1 2 3 4 5 6 7 8 9 10

Now we rotate the order of all values in the vector
in so that the fourth value becomes the first value.

Here are the revised contents of the vector:
4 5 6 7 8 9 10 1 2 3

Next we rotate the order of the 2nd to the 6th values in the vector so that
the third value in that group of values becomes the first value of the group.

Here are the revised contents of the vector:
4 7 8 9 5 6 10 1 2 3

See Also