for_each |
Apply a function to every item in a range.
Apply f to every element in the range [ first , last) and return the input parameter f .
#include <algorithm>
template< class InputIterator, class Function >
Function for_each
(
InputIterator first,
InputIterator last,
Function f
);
Time complexity is linear, as function
is called ( last - first
) times. Space complexity is constant.
#include <iostream>
#include <algorithm>
void
print( int a_ )
{
cout << a_ << ` `;
}
int numbers[ 10 ] = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };
void
main()
{
for_each( numbers, numbers + 10, print );
cout << "\n";
}
1 1 2 3 5 8 13 21 34 55
#include <iostream>
#include <algorithm>
#include <vector>
void
print_sqr( int a_ )
{
cout << a_ * a_ << " ";
}
void
main()
{
vector< int > v( 10 );
for ( size_t i = 0; i < v.size(); ++i )
v[ i ] = i;
for_each( v.begin(), v.end(), print_sqr );
cout << "\n";
}
0 1 4 9 16 25 36 49 64 81
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.