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.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Check C++ Books
- Apply for Computer Science Internship
- Check Programming Books
- Practice Computer Science MCQs
- Check Computer Science Books