reverse() Function in C++

This C++ program demonstrates the reverse() algorithm. The function reverse() takes two iterators as parameters and reverses the order of the elements of the container. The program creates a string array and reverses the order of the strings.

Here is the source code of the C++ program which demonstrates the reverse() 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() algorithm
  3.  */
  4.  
  5. #include <iostream>
  6. #include <algorithm>
  7. #include <vector>
  8. #include <iomanip>
  9. using namespace std;
  10.  
  11. void print(string a[], int N)
  12. {   
  13.     for(int i = 0; i < N; i++)
  14.     {
  15.         cout << (i + 1) << ". " << setw(5)
  16.              << a[i] << "  ";
  17.     }
  18.     cout << endl;
  19. }
  20.  
  21. int main()
  22. {
  23.     string s[] = {"George", "John", "Lucy", "Alice", "Bob", "Watson"};
  24.  
  25.     cout << "Original order : ";
  26.     print(s, 6);
  27.     cout << "Reversing the order ... " << endl;
  28.     reverse(s, s + 6);
  29.     cout << "Reversed order : ";
  30.     print(s, 6);
  31. }

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

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.