![]() |
VOOZH | about |
std::rotate() is a C++ STL algorithm defined in the <algorithm> header that rearranges elements in a range so that a specified iterator becomes the new first element. It works with containers that provide at least forward iterators (such as arrays, vector, and list), performs the rotation in place, returns an iterator to the new position of the original first element.
3 4 5 1 2
Explanation: The rotate() function rotates the range so that the specified element (v.begin() + 2 here) becomes the first element. Rotation can be clockwise (right) or anticlockwise.
The rotate() function is defined in the <algorithm> header file.
rotate(first, mid, last);
Parameters:
Return Value:
The rotation operation can be done in two ways:
Right Rotation
Right rotation of a vector involves shifting all elements to the right by a specified number of positions. The elements shifted out from the right end are wrapped around to the left end of the vector.
Example 2: Right Rotate an Array
4 5 1 2 3
Explanation: This code rotates the array to the right by d positions by making the element at position n - d the new first element.
Left Rotation
Left rotation of a vector means shifting all the elements of the vector to the left by a specified number of positions. The elements that are shifted out from the left end are wrapped around to the right end of the vector.
The examples below demonstrate how to use the rotate() function on different types of data containers for left rotation (anticlockwise) and right rotation (clockwise).
Example 1: Left Rotate an Array
3 4 5 1 2
Explanation:This code performs a left rotation of the array by d positions by rotating the range so that arr + d becomes the starting element.
Example 3: Left Rotate a List
3 4 5 1 2
Explanation: This code left-rotates the list by two positions using std::rotate() and next() to obtain the middle iterator for a non-random-access container.