The function is defined in header <algorithm>. It rotates the order of the elements in the range [first,last], in such a way that the element pointed by middle becomes the new first element.
Function Template :
void rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last)
first, last : Forward Iterators to the initial and final positions of the sequence to be rotated
middle : Forward Iterator pointing to the element within the range [first, last] that is moved to the first position in the range.
Types of Rotations
- Left Rotation : To rotate left, we need to add the vector index. For example, you have to rotate vector left 3 times. The 3th index of vector becomes first element. vec.begin() + 3 will rotate vector 3 times left.
- Right Rotation : To rotate right, we need to subtract the vector index. For example, you have to rotate vector right 3 times. The 3th last index of vector becomes first element. vec.begin()+vec.size()-3 will rotate vector 3 times right.
- std::rotate vs std::rotate_copy in C++ STL
- How to fix auto keyword error in Dev-C++
- Lexicographical smallest number after at most K consecutive swaps
- Important functions of STL Components in C++
- Array of Structures vs. Array within a Structure in C/C++
- Difference between cout and puts() in C++ with Examples
- Difference between forward list and list in C++
- Short-Circuiting in C++ and Linux
- Different types of range-based for loop iterators in C++
- Learn C++ Programming Step by Step - A 20 Day Curriculum!
- Check if Array elements can be maximized upto M by adding all elements from another array
- Why do we need reference variables if we have pointers
- Similarities and Difference between Java and C++
- Macros and its types in C/C++
Input : 1 2 3 4 5 6 7 8 9
Old vector : 1 2 3 4 5 6 7 8 9
New vector : 4 5 6 7 8 9 1 2 3 // Rotated at 3th position, starting index as 0.
Input : 8 2 4 6 11 0 15 8
Old vector : 8 2 4 6 11 0 15 8
New vector : 0 15 8 8 2 4 6 11 //Rotated at 5th position, starting index as 0.
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
Time Complexity : Theta(n) where n is the number of elements in the given range.
This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.