C++98 recap
I needed to run through old C++98 before learning new C++11 features.
code
struct is_even : unary_function{ bool operator()(int x) const { return x % 2 == 0; } }; struct buggy_plus : binary_function { int operator()(int a, int b) const { return a + b + 1; } }; void Hoge::TestFunctionObjects() { // standard function objects plus<int> plus; minus<double> minus; cout << "plus(2,3) = " << plus(2, 3) << endl; cout << "minus(2.0f,0.2f) = " << minus(2.0f, 0.2f) << endl; // custom unary function objects is_even even; unary_negate<is_even> odd(even); cout << "Is 2 even? " << even(2) << endl; cout << "Is 2 odd? " << odd(2) << endl; // custom binary function objects buggy_plus bplus; cout << "bplus(2,3) = " << bplus(2, 3) << endl; } void Hoge::TestAlgorithm() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } // algorithm sort(v.begin(), v.end(), greater<int>()); cout << "---" << endl; for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout << *it << endl; } // remove_if doesn't remove the element, but swap the matched ones to backword and return the last pointer vector<int>::iterator last = remove_if(v.begin(), v.end(), bind2nd(less<int>(), 5)); cout << "---" << endl; for (vector<int>::iterator it = v.begin(); it != last; it++) { cout << *it << endl; } }
result
* function objects plus(2,3) = 5 minus(2.0f,0.2f) = 1.8 Is 2 even? 1 Is 2 odd? 0 bplus(2,3) = 6 * algorighm --- 9 8 7 6 5 4 3 2 1 0 --- 9 8 7