std :: reverse_copy in C++ STL

C++ STL provides a function that copies the elements from the given range but in reverse order. Below is a simple program to show the working of reverse_copy().

Examples:

Input : 1 2 3 4 5 6 7 8 9 10
Output : The vector is: 
10 9 8 7 6 5 4 3 2 1

The function takes three parameters. The first two are the range of the elements which are to be copied and the third parameter is the starting point from where the elements are to be copied in reverse order.



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to copy from array to vector
// using reverse_copy() in STL.
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    int src[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int n = sizeof(src) / sizeof(src[0]);
  
    vector<int> dest(n);
  
    reverse_copy(src, src + n, dest.begin());
  
    cout << "The vector is: \n";
    for (int x : dest) {
        cout << x << " ";
    }
  
    return 0;
}

chevron_right


Output:

The vector is: 
10 9 8 7 6 5 4 3 2 1

Below is an example of vector to vector copy.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to copy from array to vector
// using reverse_copy() in STL.
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> src { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  
    vector<int> dest(src.size());
  
    reverse_copy(src.begin(), src.end(), dest.begin());
  
    cout << "The vector is: \n";
    for (int x : dest) {
        cout << x << " ";
    }
  
    return 0;
}

chevron_right


Output:

The vector is: 
10 9 8 7 6 5 4 3 2 1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.