I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

for_each

Performs an operation for each element
+ View version details

Key Facts

Gyroscopic Couple: The rate of change of angular momentum (\inline \tau) = \inline I\omega\Omega (In the limit).
  • \inline I = Moment of Inertia.
  • \inline \omega = Angular velocity
  • \inline \Omega = 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.

Return Value

Returns the function object.

Complexity

The complexity is linear with at most (last - first) comparisons.
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
References

See Also