Friday, April 26, 2013

C++: Good old for_each again

 

http://en.cppreference.com/w/cpp/algorithm/for_each

Example

The following example uses a lambda function to increment all of the elements of a vector and then computes a sum of them:

run this code

#include <vector>
#include <algorithm>
#include <iostream>   struct Sum {
Sum() { sum = 0; }
void operator()(int n) { sum += n; }   int sum;
};   int main()
{
std::vector<int> nums{3, 4, 2, 9, 15, 267};   std::cout << "before: ";
for (auto n : nums) {
std::cout << n << " ";
}
std::cout << '\n';   std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });
Sum s = std::for_each(nums.begin(), nums.end(), Sum());   std::cout << "after: ";
for (auto n : nums) {
std::cout << n << " ";
}
std::cout << '\n';
std::cout << "sum: " << s.sum << '\n';
}

No comments:

Post a Comment