Home » C++ algorithm rotate() function

C++ algorithm rotate() function

by Online Tutorials Library

C++ Algorithm rotate()

C++ Algorithm rotate() function is used to rotate the order of the elements within a range [first, last).

  • The sequence will start at the element in the middle of the source sequence and the last element will be followed by first.
  • middle to the elements between the middle and the last element.

Syntax

Parameter

first: A forward iterator pointing the position of the first element in the range to be rotated.

middle: A forward iterator addressing to the element within the range [first, last) that is moved to the first position in the range.

last: A forward iterator pointing the position one past the final element in the range in which the elements are being reversed.

Return value

None

Complexity

Complexity is linear in the range [first, last): swaps or moves elements until all elements have been relocated.

Data races

The object in the range [first, last) are modified.

Exceptions

This function throws an exception if either an element swap or move or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let’s see the simple example to rotate the given string:

Output:

Before Rotate : Hello  After Rotate  : lloHe  

Example 2

Let’s see another simple example:

Output:

Original order : 1. A   2. B   3. C   4. D   5. E   6. G   7. H     Rotate with 'C' as middle element  Rotated order  : 1. C   2. D   3. E   4. G   5. H   6. A   7. B     Rotate with 'G' as middle element  Rotated order  : 1. G   2. H   3. A   4. B   5. C   6. D   7. E     Rotate with 'A' as middle element  Original order : 1. B   2. C   3. D   4. E   5. G   6. H   7. A     

Example 3

Let’s see another simple example:

Output:

Old vector : 1 2 3 4 5 6 7 8 9  New vector after left rotation : 4 5 6 7 8 9 1 2 3    Old vector : 1 2 3 4 5 6 7 8 9  New vector after right rotation : 6 7 8 9 1 2 3 4 5  

Example 4

Let’s see another simple example:

Output:

Vector v1 is ( -3 -2 -1 0 1 2 3 4 5 ).  After rotating, vector v1 is ( 0 1 2 3 4 5 -3 -2 -1 ).  The original deque d1 is ( 0 1 2 3 4 5 ).  After the rotation of a single deque element to the back,   d1 is   ( 1 2 3 4 5 0 ).  After the rotation of a single deque element to the back,   d1 is   ( 2 3 4 5 0 1 ).  After the rotation of a single deque element to the back,   d1 is   ( 3 4 5 0 1 2 ).  After the rotation of a single deque element to the back,   d1 is   ( 4 5 0 1 2 3 ).  After the rotation of a single deque element to the back,   d1 is   ( 5 0 1 2 3 4 ).  After the rotation of a single deque element to the back,   d1 is   ( 0 1 2 3 4 5 ).  

Next TopicC++ Algorithm

You may also like