Skip to content
Related Articles

Related Articles

for_each loop in C++
  • Difficulty Level : Medium
  • Last Updated : 05 Mar, 2021

Apart from the generic looping techniques, such as “for, while and do-while”, C++ in its language also allows us to use another functionality which solves the same purpose termed “for-each” loops. This loop accepts a function which executes over each of the container elements. This loop is defined in the header file “algorithm”, and hence has to be included for successful operation of this loop.

  • It is versatile, i.e can work with any container.
  • It reduces chances of errors one can commit using generic for loop
  • It makes code more readable
  • for_each loops improve overall performance of code

Syntax:  

for_each (InputIterator first, InputIterator last, Function fn)

strt_iter : The beginning position 
from where function operations has to be executed.
last_iter : This ending position 
till where function has to be executed.
fnc/obj_fnc : The 3rd argument is a function or 
an object function which operation would be applied to each element. 

CPP




// C++ code to demonstrate the
// working of for_each loop
 
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
// helper function 1
void printx2(int a)
{
    cout << a * 2 << " ";
}
 
// helper function 2
// object type function
struct Class2
{
    void operator() (int a)
    {
        cout << a * 3 << " ";
    }
} ob1;
 
 
int main()
{
     
    // initializing array
    int arr[5] = { 1, 5, 2, 4, 3 };
     
    cout << "Using Arrays:" << endl;
     
    // printing array using for_each
    // using function
    cout << "Multiple of 2 of elements are : ";
    for_each(arr, arr + 5, printx2);
     
    cout << endl;
     
    // printing array using for_each
    // using object function
    cout << "Multiple of 3 of elements are : ";
    for_each(arr, arr + 5, ob1);
     
    cout << endl;
     
    // initializing vector
    vector<int> arr1 = { 4, 5, 8, 3, 1 };
     
    cout << "Using Vectors:" << endl;
     
     
    // printing array using for_each
    // using function
    cout << "Multiple of 2 of elements are : ";
    for_each(arr1.begin(), arr1.end(), printx2);
     
    cout << endl;
     
    // printing array using for_each
    // using object function
    cout << "Multiple of 3 of elements are : ";
    for_each(arr1.begin(), arr1.end(), ob1);
     
    cout << endl;
     
}
Output
Using Arrays:
Multiple of 2 of elements are : 2 10 4 8 6 
Multiple of 3 of elements are : 3 15 6 12 9 
Using Vectors:
Multiple of 2 of elements are : 8 10 16 6 2 
Multiple of 3 of elements are : 12 15 24 9 3 

Exceptions and for_each

In the cases of exceptions, if the function throws an exception, for_each loop will also throw an exception and break/terminate the loop. 



CPP




// C++ code to demonstrate the working
// of for_each with Exception
 
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
// Helper function 1
void printx2(int a)
{
    cout << a * 2 << " ";
    if ( a % 2 == 0)
    {
        throw a;
    }
     
}
 
// Helper function 2
// object type function
struct Class2
{
    void operator() (int a)
    {
        cout << a * 3 << " ";
        if ( a % 2 == 0)
        {
            throw a;
             
        }
    }
} ob1;
 
 
int main()
{
     
    // Initializing array
    int arr[5] = { 1, 5, 2, 4, 3 };
     
    cout << "Using Array" << endl;
     
    // Printing Exception using for_each
    // using function
    try
    {
        for_each(arr, arr + 5, printx2);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
    cout << endl;
     
    // Printing Exception using for_each
    // using object function
    try
    {
        for_each(arr, arr + 5, ob1);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
     
    // Initializing vector
    vector<int> arr1 = { 1, 3, 6, 5, 1 };
     
    cout << "\nUsing Vector" << endl;
     
    // Printing Exception using for_each
    // using function
    try
    {
        for_each(arr1.begin(), arr1.end(), printx2);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
    cout << endl;
     
    // printing Exception using for_each
    // using object function
    try
    {
        for_each(arr1.begin(), arr1.end(), ob1);
    }
    catch(int i)
    {
        cout << "\nThe Exception element is : " << i ;
    }
}
Output
Using Array
2 10 4 
The Exception element is : 2
3 15 6 
The Exception element is : 2
Using Vector
2 6 12 
The Exception element is : 6
3 9 18 
The Exception element is : 6

Using Lambdas:

With the introduction of lambda functions, this can be easily used to make the whole thing inline which is very compact and useful for people looking for using functional programming.

C++




#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
int main()
{
 
    vector<int> vec{ 1, 2, 3, 4, 5 };
 
    // this increases all the values in the vector by 1;
    for_each(vec.begin(), vec.end(), [](int& a) { a++; });
 
    // this prints all the values in the vector;
    for_each(vec.begin(), vec.end(),
             [](int a) { cout << a << " " << endl; });
 
    return 0;
}
Output
2 
3 
4 
5 
6 

This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :