C++ Standard Library C++ STL Library

C++ <algorithm> - for_each() Function



The C++ algorithm::for_each function is used to apply the specified function fn to each element in the range [first, last).

Syntax

template <class InputIterator, class Function>
   Function for_each (InputIterator first, 
                      InputIterator last, 
                      Function fn);

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
fn Specify unary function which accepts an element in the range as argument.

Return Value

Returns fn.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::for_each function is used to apply function called print on the given range.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
void print (int i) {  
  cout<<i<<" ";
}  

int main () {
  vector<int> vec{1, 2, 3, 4, 5, 6, 7};
  vector<int>::iterator it;

  //apply print function for a given range
  cout<<"vec contains: ";
  for_each(vec.begin(), vec.end(), print);

  return 0;
}

The output of the above code will be:

vec contains: 1 2 3 4 5 6 7 

❮ C++ <algorithm> Library