unary_function Program in C++

bookmark

#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;
}

Ouput:
Range 1 : 20 
Elements divisible by 4 : 4 8 12 16 20