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.
/*
* C++ Program to illustrate unary function objects bases
*/
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
struct DivisibleByFour : public std::unary_function<int, bool> {
bool operator() (int value)
{
if ((value % 4) == 0)
{
std::cout << value << " ";
return true;
}
else
return false;
}
};
int main()
{
DivisibleByFour d;
std::vector <int> v(20);
for (int i = 0; i < 20; i++)
v[i] = i + 1;
std::cout << "Range 1 : 20 " << std::endl;
std::cout << "Elements divisible by 4 : ";
std::for_each(v.begin(), v.end(), d);
std::cout << std::endl;
}
$ a.out Range 1 : 20 Elements divisible by 4 : 4 8 12 16 20
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.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Programming Books
- Apply for Information Technology Internship
- Practice Programming MCQs
- Buy C++ Books
- Buy Computer Science Books