Or login with:
#include <algorithm> template < class InputIterator, class Function> Function for_each ( InputIterator first, InputIterator last, Function f );Parameters:
| Parameter | Description |
|---|---|
| first | An input iterator addressing the position of the first element in the range to be operated on |
| last | An input iterator addressing the position one past the final element in the range operated on |
| f | User-defined function object that is applied to each element in the range |
#include <vector> #include <algorithm> 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'; return 0; }
You must login to leave a messge