sort() Function in C++

This C++ program demonstrates the sort() algorithm. The program creates a vector of strings, sorts them using sort algorithm without predicate to sort them in default order and with greater predicate to sort them in reverse order and prints it.

Here is the source code of the C++ program which demonstrates the sort() 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 sort container elements using-sort algorithm
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <functional>
  8.  
  9. void print(const std::vector <std::string>& v)
  10. {
  11.     std::vector <std::string>::const_iterator i;
  12.     for(i = v.begin(); i != v.end(); i++)
  13.     {
  14.         std::cout << *i << "    ";
  15.     }
  16.     std::cout << std::endl;
  17. }
  18.  
  19. int main()
  20. {
  21.     std::vector <std::string> v;
  22.     // Push functional programming languages
  23.     v.push_back("Lisp");
  24.     v.push_back("Elixir");
  25.     v.push_back("Erlang");
  26.     v.push_back("F#");
  27.     v.push_back("Haskell");
  28.     v.push_back("Kogut");
  29.     v.push_back("Scala");
  30.  
  31.     // sort without predicate
  32.     std::sort(v.begin(), v.end());
  33.     std::cout << "Sorted list of functional programming languages - " << std::endl;
  34.     print(v);
  35.     // sort with predicate
  36.     std::sort(v.begin(), v.end(), std::greater<std::string>());
  37.     std::cout << "Reverse Sorted list of functional programming languages - " << std::endl;
  38.     print(v);
  39. }

$ a.out
Sorted list of functional programming languages - 
Elixir    Erlang    F#    Haskell    Kogut    Lisp    Scala    
Reverse Sorted list of functional programming languages - 
Scala    Lisp    Kogut    Haskell    F#    Erlang    Elixir

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.