rotate


Rotate a sequence by n positions.

Rotate the sequence [ first ... last ) to the left by ( middle - first ) positions.

Library

Standards<ToolKit>

Declaration


#include <algorithm>

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

Complexity

Time complexity is linear. Space complexity is constant.

Example <ospace/osstd/examples/rotate0.cpp>
#include <iostream>
#include <algorithm>

int numbers[ 6 ] = { 0, 1, 2, 3, 4, 5 };

void
main()
  {
  rotate( numbers, numbers + 2, numbers + 6 );

  for ( int i = 0; i < 6; ++i )
    cout << numbers[ i ] << ` `;
  cout << "\n";
  }

3 4 5 0 1 2
Example <ospace/osstd/examples/rotate1.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

void
main()
  {
  vector< int > v1( 10 );
  for ( int j = 0; j < v1.size(); ++j )
    v1[ j ] = j;
  ostream_iterator< int > iter( cout, " " );
  copy( v1.begin(), v1.end(), iter );
  cout << "\n";

  for ( int i = 0; i < v1.size(); ++i )
    {
    rotate( v1.begin(), v1.begin() + i, v1.end() );

    ostream_iterator< int > iter( cout, " " );
    copy( v1.begin(), v1.end(), iter );
    cout << "\n";
    }

  cout << "\n";
  }

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 0
3 4 5 6 7 8 9 0 1 2
6 7 8 9 0 1 2 3 4 5
0 1 2 3 4 5 6 7 8 9
5 6 7 8 9 0 1 2 3 4
1 2 3 4 5 6 7 8 9 0
8 9 0 1 2 3 4 5 6 7
6 7 8 9 0 1 2 3 4 5
5 6 7 8 9 0 1 2 3 4

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.