for_each Loop in C++

C++ for_each loop accepts a function that executes over each of the container elements.

This loop is defined in the header file <algorithm> and hence has to be included for the successful operation of this loop.

Syntax of for_each Loop

for_each ( InputIterator start_iter, InputIterator last_iter, Function fnc);

Parameters

  • start_iter: Iterator to the beginning position from where function operations have to be executed.
  • last_iter: Iterator to the ending position till where function has to be executed.
  • fnc: The 3rd argument is a function or a function object which would be executed for each element.

Example of for_each Loop

The below example demonstrates the use of for_each loop in a C++ program.

C++




// C++ Program to show use of for_each loop
  
#include <bits/stdc++.h>
using namespace std;
  
// function to print values passed as parameter in loop
void printValues(int i) { cout << i << " " << endl; }
  
int main()
{
    // initializing vector
    vector<int> v = { 1, 2, 3, 4, 5 };
  
    // iterating using for_each loop
    for_each(v.begin(), v.end(), printValues);
  
    return 0;
}


Output

1 
2 
3 
4 
5 

Explanation:
The above program uses for_each loop to iterate through each element of the vector (v here), it calls the printValues function to print each element. Output is displayed in the next line for each iteration.

Related Articles



for Loop in C++

In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific number of iterations.

for loop is generally preferred over while and do-while loops in case the number of iterations is known beforehand.

Similar Reads

Syntax of for Loop

The syntax of for loop in C++ is shown below:...

Flowchart of for Loop in C++

Flowchart of for Loop in C++...

Examples of for Loop in C++

Example 1...

C++ Nested for Loop

...

Multiple Variables in for Loop

...

C++ Infinite for Loop

...

Range-Based for Loop in C++

A nested for loop is basically putting one loop inside another loop. Every time the outer loop runs, the inner loop runs all the way through. It’s a way to repeat tasks within tasks in your program....

for_each Loop in C++

...