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

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.