/* * function-objects-02.cc Standard Library, Funtion objects, exercise 2. */ #include #include #include #include #include #include using namespace std; using namespace std::placeholders; template ostream& operator<<(ostream& os, const vector& v) { copy(begin(v), end(v), ostream_iterator(os, " ")); return os; } template struct greater_than { bool operator()(const T& value) const { return value_ < value; } typedef bool result_type; typedef T argument_type; }; template struct not_equal { bool operator()(const T& value) const { return !(value_ == value); // if != not present } typedef bool result_type; typedef T argument_type; }; template struct multiply_by { T operator()(const T& value) const { return factor_ * value; } typedef T result_type; typedef T argument_type; }; int main() { vector v{ 5, 4, 12, 8, 2, 1, 3, 10, 9, 7, 6, 11 }; cout << "\nValues in the vector:\n" << v << "\n\n"; ostream_iterator out(cout, " "); // a) cout << "Values in the vector greater than 5:\n"; copy_if(begin(v), end(v), out, ::greater_than()); cout << "\n\n"; cout << "Values in the vector greater than 5 (only std):\n"; remove_copy_if(begin(v), end(v), out, bind(less_equal(), _1, 5)); cout << "\n\n"; // b) cout << "Values in the vector not equal to 10:\n"; copy_if(begin(v), end(v), out, not_equal()); cout << "\n\n"; cout << "Values in the vector not equal to 10 (only std):\n"; copy_if(begin(v), end(v), out, bind(not_equal_to(), 10, _1)); cout << "\n\n"; // c) cout << "Multiply each value in the vector by 2:\n"; transform(begin(v), end(v), begin(v), multiply_by()); cout << v << "\n\n"; cout << "Multiply each value in the vector by 2 again (only std):\n"; transform(begin(v), end(v), begin(v), bind(multiplies(), _1, 2)); cout << v << "\n\n"; }