Skip to content
Related Articles

Related Articles

std::rotate vs std::rotate_copy in C++ STL

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 05 Aug, 2017
View Discussion
Improve Article
Save Article
  1. rotate in STL: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, i, e, to the left.




    // Illustrating the use of rotate algorithm
    #include <bits/stdc++.h>
    using namespace std;
      
    // Driver Program
    int main()
    {
        vector<int> arr;
      
        // set some values: 1 2 3 4 5 6
        // 7 8 9
        for (int i = 1; i < 10; ++i)        
            arr.push_back(i);
      
        // Use of rotate
        rotate(arr.begin(), arr.begin() + 3, arr.end());
      
        // prints the content:
        cout << "arr contains:";
        for (auto i = arr.begin(); i != arr.end(); i++)
            cout << ' ' << *i;
        cout << endl;
      
        return 0;
    }

    Output:

    arr contains: 4 5 6 7 8 9 1 2 3
    
  2. rotate_copy:It copies the elements in the range [first, last) to the range beginning at result, but rotates the order of the elements in such a way that the element pointed by middle becomes the first element in the resulting range, i.e, left rotate.




    // Illustrating the use of rotate_copy
    #include <bits/stdc++.h>
    using namespace std;
      
    // Driver Program
    int main()
    {
        int arr[] = { 10, 20, 30, 40, 50, 60, 70 };    
      
        // Use of rotate_copy
        vector<int> gfg(7);
        rotate_copy(arr, arr + 3, arr + 7, gfg.begin());
      
        // prints the content:
        cout << "gfg contains:";
        for (auto i = gfg.begin(); i != gfg.end(); i++)
            cout << ' ' << *i;
        cout << endl;
      
        return 0;
    }

    Output:

    gfg contains: 40 50 60 70 10 20 30
    

This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!