Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report
  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
    


Last Updated : 05 Aug, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads