Name
for_each function template — Calls a function for each item in a range
Synopsis
template<typename InIter, typename Func>
Function for_each(InIter first, InIter last, Func f);
The for_each
function
template calls f
for each item in
the range [first
, last
), passing the item as the sole
argument to f
. It returns
f
.
Example
Example 13-1 shows
how the use for_each
to test
whether a sequence is sorted. The is_sorted
object remembers the previous
item in the sequence, which it compares with the current item. The
overloaded bool
operator returns
true
if the sequence is sorted so
far or false
if the sequence is
out of order. The example takes advantage of the fact that for_each
returns the f
parameter as its result.
#include <iostream>
#include <algorithm>
#include <list>
template<typename T>
class is_sorted
{
public:
is_sorted( ) : first_time(true), sorted(true) {}
void operator( )(const T& item) {
// for_each calls operator( ) for each item.
if (first_time)
first_time = false;
else if (item < prev_item)
sorted = false;
prev_item = item;
}
operator bool( ) { return sorted; }
private:
bool first_time;
bool sorted;
T prev_item;
};
int main( )
{
std::list<int> l;
l.push_back(10);
l.push_back(20);
... if (std::for_each(l.begin( ), l.end( ), is_sorted<int>( )))
std::cout << "list is sorted" << '\n';
}
Technical Notes
Complexity is linear: f
is
called exactly last - first times.
See Also
copy function template,
accumulate
in <numeric>
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.