1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
using namespace std;
template <class Predicate>
void print_if(int * array, unsigned size, Predicate pred)
{
for (unsigned i = 0; i < size; ++i)
if ( pred(array[i]) )
cout << array[i] << " ";
cout << endl;
}
bool is_positive(int n) { return (n > 0); }
bool is_negative(int n) { return (n < 0); }
struct is_greater_than
{
int val;
is_greater_than(int v): val(v) {}
bool operator () (int n) { return (n > val); }
};
struct is_less_than
{
int val;
is_less_than(int v): val(v) {}
bool operator () (int n) { return (n < val); }
};
int main()
{
int my_array[] = { 1, 2, -1, 3, -4, 5, 10, -9, 0, 32 };
print_if(my_array, 10, is_positive);
print_if(my_array, 10, is_negative);
print_if(my_array, 10, is_less_than(2));
print_if(my_array, 10, is_greater_than(2));
return 0;
}
|