lexicographical_compare() in C++

«
»
This C++ program demonstrates the lexicographical_compare() algorithm. The lexicographical_compare function takes five parameters – the four parameters are begin and end iterators to the two containers and the fifth parameter is a predicate. The predicate we are using is equal_to which is defined in the functional library.

Here is the source code of the C++ program which demonstrates the lexicographical_compare() 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 demonstrate the lexicographical_compare() algorithm
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7. #include <functional>
  8.  
  9. void print(const std::vector <int>& v)
  10. {
  11.     std::vector <int>::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 <int> a(10), b(10);
  22.     bool result;
  23.  
  24.     for (int i = 0; i < 10 ;i++)
  25.     {
  26.         a[i] = i + 1;
  27.         b[i] = i + 1;
  28.     }
  29.     std::cout << "a : ";
  30.     print(a);
  31.     std::cout << "b : ";
  32.     print(b);
  33.     // Comparing a and b lexicographically
  34.     result = std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), std::equal_to <int>());
  35.     if(result == true)
  36.     {
  37.         std::cout << "a is lexicographically equal to b."
  38.                   << std::endl;
  39.     }
  40.     else
  41.     {
  42.         std::cout << "a is lexicographically not equal to b."
  43.                   << std::endl;
  44.     }
  45. }

$ a.out
a : 1 2 3 4 5 6 7 8 9 10 
b : 1 2 3 4 5 6 7 8 9 10 
a is lexicographically equal to b.

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

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

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 & technical discussions at Telegram SanfoundryClasses.