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
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.