unary_function Program in C++

This C++ program illustrates unary function object base. The DivisibleByFour inherits from the unary_function object base defined in functional library and is passed as a predicate to the for_each algorithm. The elements of vector which are divisible by four are printed.

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 unary function objects bases 
  3.  */
  4. #include <iostream>
  5. #include <functional>
  6. #include <vector>
  7. #include <algorithm>
  8.  
  9. struct DivisibleByFour : public std::unary_function<int, bool> {
  10.     bool operator() (int value)
  11.     {
  12.         if ((value % 4) == 0)
  13.         {
  14.             std::cout << value << " ";
  15.             return true;
  16.         }
  17.         else
  18.             return false;
  19.     }
  20. };
  21.  
  22. int main()
  23. {
  24.     DivisibleByFour d;
  25.     std::vector <int> v(20);
  26.  
  27.     for (int i = 0; i < 20; i++)
  28.         v[i] = i + 1;
  29.     std::cout << "Range 1 : 20 " << std::endl;
  30.     std::cout << "Elements divisible by 4 : ";
  31.     std::for_each(v.begin(), v.end(), d);
  32.     std::cout << std::endl;
  33. }

$ a.out
Range 1 : 20 
Elements divisible by 4 : 4 8 12 16 20

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.