\\
Performs an operation for each element
Key Facts
Gyroscopic Couple: The rate of change of angular momentum () = (In the limit).- = Moment of Inertia.
- = Angular velocity
- = Angular velocity of precession.
Blaise Pascal (1623-1662) was a French mathematician, physicist, inventor, writer and Catholic philosopher.
Leonhard Euler (1707-1783) was a pioneering Swiss mathematician and physicist.
Definition
The for_each() algorithm is defined in the standard header <algorithm>, and in the nonstandard backward-compatibility header <algo.h>.Interface
#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 |
Description
The for_each() algorithm applies a specified function object to each element in a forward order within a range.References
Example:
Example - lambda function
Problem
The following example uses a lambda function to increment all of the elements of a vector and then computes a sum of them.
Workings
#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; }
Solution
Output:
before: 3 4 2 9 15 267
after: 4 5 3 10 16 268
sum: 306
after: 4 5 3 10 16 268
sum: 306
References