std :: reverse_copy in C++ STL
Last Updated :
11 Jun, 2018
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.
#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;
}
|
Output:
The vector is:
10 9 8 7 6 5 4 3 2 1
Below is an example of vector to vector copy.
#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;
}
|
Output:
The vector is:
10 9 8 7 6 5 4 3 2 1
Share your thoughts in the comments
Please Login to comment...