Skip to content
Related Articles

Related Articles

Improve Article

std :: reverse_copy in C++ STL

  • Difficulty Level : Easy
  • 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.




// 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;
}
Output:
The vector is: 
10 9 8 7 6 5 4 3 2 1

Below is an example of vector to vector copy.




// 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;
}
Output:
The vector is: 
10 9 8 7 6 5 4 3 2 1
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :