reverse_copy() in C++

This C++ program demonstrates the reverse_copy() algorithm. The function reverse_copy() takes three iterators as parameters – two iterators to the beginning and the end of the container elements to be reversed and the third iterator to the container where reversed elements are to be saved. The program demonstrates the use of the algorithm which doesn’t modify the order of the container whose order is being reversed.

Here is the source code of the C++ program which demonstrates the reverse_copy() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to reverse the order of elements using reverse_copy() algorithm
  3.  */
  4.  
  5. #include <iostream>
  6. #include <algorithm>
  7. #include <vector>
  8. #include <iomanip>
  9. #include <iterator>
  10. using namespace std;
  11.  
  12. void print(string a[], int N)
  13. {   
  14.     for(int i = 0; i < N; i++)
  15.     {
  16.         cout << (i + 1) << ". " << setw(5)
  17.              << a[i] << "  ";
  18.     }
  19.     cout << endl;
  20. }
  21.  
  22. int main()
  23. {
  24.     string s[] = {"George", "John", "Lucy", "Alice", "Bob", "Watson"};
  25.     string t[6];
  26.  
  27.     cout << "Original order : ";
  28.     print(s, 6);
  29.     cout << "Reversing the order ... " << endl;
  30.     // Doesn't modify original array s[]
  31.     reverse_copy(s, s + 6, t);
  32.     cout << "Original order : ";
  33.     print(s, 6);
  34.     cout << "Reversed order : ";
  35.     print(t, 6);
  36. }

$ a.out
Original order : 1. George  2.  John  3.  Lucy  4. Alice  5.   Bob  6. Watson  
Reversing the order ... 
Original order : 1. George  2.  John  3.  Lucy  4. Alice  5.   Bob  6. Watson  
Reversed order : 1. Watson  2.   Bob  3. Alice  4.  Lucy  5.  John  6. George  4

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.