binary_function Program in C++

This C++ program illustrates binary function object base. The Compare inherits from the binary_function object base defined in functional library. The numbers taken from input are passed to the function object and a boolean result is returned. If the result is true, the numbers are equal otherwise they are unequal.

Here is the source code of the C++ program illustrates unary function object base. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate binary function objects bases 
  3.  */
  4. #include <iostream>
  5. #include <functional>
  6. #include <algorithm>
  7.  
  8. struct Compare : public std::binary_function<int, int, bool> {
  9.     bool operator() (int a, int b)
  10.     {
  11.         return (a == b);
  12.     }
  13. };
  14.  
  15. int main()
  16. {
  17.     Compare compare;
  18.     Compare::first_argument_type a;
  19.     Compare::first_argument_type b;
  20.     Compare::result_type r;
  21.  
  22.     std::cout << "Enter a = ";
  23.     std::cin  >> a;
  24.     std::cout << "Enter b = ";
  25.     std::cin  >> b;
  26.     r = compare(a, b);
  27.     std::cout << "Numbers " << a << " and " << b;
  28.     if(r == true)
  29.         std::cout << " are equal.\n";
  30.     else
  31.         std::cout << " are unequal.\n";
  32. }

$ a.out
Enter a = 10
Enter b = 20
Numbers 10 and 20 are unequal.
$ a.out
Enter a = 10
Enter b = 10
Numbers 10 and 10 are equal.

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.