#include <algorithm>
#include <iostream>
#include <vector>
// *** before: ***
// a small piece of code passed to an algorithm had to become a class
// with operator(), written far away from the place where it is used
struct Greater {
int bound;
explicit Greater(int b) : bound(b) {}
bool operator()(int n) const { return n > bound; }
};
struct Adder {
int* total;
explicit Adder(int* t) : total(t) {}
void operator()(int n) const { *total += n; }
};
int countOld(const std::vector<int>& v, int bound) {
return static_cast<int>(std::count_if(v.begin(), v.end(), Greater(bound)));
}
// *** in version C++11: ***
int countNew(const std::vector<int>& v, int bound) {
return static_cast<int>(std::count_if(v.begin(), v.end(),
[bound](int n) { return n >
bound; }));
}
int main() {
std::vector<int> v;
for (int i = 1; i <= 10; ++i) v.push_back(i);
std::cout << countOld(v, 5) << " " << countNew(v, 5) << "\n";
int total = 0;
std::for_each(v.begin(), v.end(), [&total](int n) { total += n; }); // by
//reference
std::cout << total << "\n";
auto multiply = [](int a, int b) { return a * b; }; // stored in a variable
std::cout << multiply(6, 7) << "\n";
// [=] copies everything used, [&] takes everything by reference
int factor = 3;
std::for_each(v.begin(), v.end(), [=](int n) { std::cout << n * factor <<
" "; });
std::cout << "\n";
}