Standard C++ Library Class Reference

Complexity
The function f is applied exactly last - first times.
Example
//
// for_each.cpp
//
#include <vector>
#include <algorithm>
#include <iostream.h>
// Function class that outputs its argument times x
template <class Arg>
class out_times_x : private unary_function<Arg,void>
{
private:
Arg multiplier;
public:
out_times_x(const Arg& x) : multiplier(x) { }
void operator()(const Arg& x)
{ cout << x * multiplier << " " << endl; }
};
int main()
{
int sequence[5] = {1,2,3,4,5};
// Set up a vector
vector<int> v(sequence,sequence + 5);
// Setup a function object
out_times_x<int> f2(2);
for_each(v.begin(),v.end(),f2); // Apply function
return 0;
}
Output : 2 4 6 8 10
Warning
If your compiler does not support default template parameters then you need to always supply
the Allocator template argument. For instance you'll have to write:
vector<int, allocator>
instead of:
vector<int>