- Modern C++ Programming Cookbook
- Marius Bancila
- 152字
- 2021-07-09 21:04:38
How to do it...
You should prefer to use lambda expressions to pass callbacks to standard algorithms instead of functions or function objects:
- Define anonymous lambda expressions in the place of the call if you only need to use the lambda in a single place:
auto numbers =
std::vector<int>{ 0, 2, -3, 5, -1, 6, 8, -4, 9 };
auto positives = std::count_if(
std::begin(numbers), std::end(numbers),
[](int const n) {return n > 0; });
- Define a named lambda, that is, one assigned to a variable (usually with the auto specifier for the type), if you need to call the lambda in multiple places:
auto ispositive = [](int const n) {return n > 0; };
auto positives = std::count_if(
std::begin(numbers), std::end(numbers), ispositive);
- Use generic lambda expressions if you need lambdas that only differ in their argument types (available since C++14):
auto positives = std::count_if(
std::begin(numbers), std::end(numbers),
[](auto const n) {return n > 0; });