The Wayback Machine - https://web.archive.org/web/20241113034820/https://www.geeksforgeeks.org/for_each-loop-c/
Open In App

for_each loop in C++

Last Updated : 12 Jul, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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”: #include<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 start_iter, InputIterator last_iter, Function fnc)

start_iter : The beginning position 
from where function operations has to be executed.
last_iter : The 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 or if any of the operations on iterators throws an exception, for_each loop will also throw an exception and break/terminate the loop. 

Note: 

  • Invalid arguments may leads to Undefined behavior.
  • For_each can not work with pointers of an array (An array pointer do not know its size, for_each loops will not work with arrays without knowing the size of an array)

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 

 
 



Previous Article
Next Article

Similar Reads

Time taken by Loop unrolling vs Normal loop
We have discussed loop unrolling. The idea is to increase performance by grouping loop statements so that there are less number of loop control instruction and loop test instructions C/C++ Code // CPP program to compare normal loops and // loops with unrolling technique #include <iostream> #include <time.h> using namespace std; int main
6 min read
Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a differential equation. It manages the devices and the systems using control loops. There are Open-Loop Control System and Closed-Loop Control System. Open-Loop Control System is used in applications in which no feedback and error handling are required. It is simple an
3 min read
Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice. Syntax: for( initializationsection ; conditional check ; increment/decrement section) { // Code to be executed } Curly braces i
5 min read
What is Routing Loop and How to Avoid Routing Loop?
Routing is a procedure that helps the packet choose an optimal path to reach its destination as soon as possible. For example, a device can be a router, which is used to handle traffic within networks. Optimal network routing methods help maintain your network operating efficiently at help in some ways i.e. faster data access and preventing overloa
3 min read
Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem. Case 1 : for (int i = 2; i <=n; i = pow(i, k)) { // some O(1) expressions or statements } In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less than or equal to n, an
1 min read
Difference Between For Loop and Do while Loop in Programming
For loop and Do while loop are control flow structures in programming that allow you to repeatedly execute a block of code. However, they differ in their syntax and use cases. It is important for a beginner to know the key differences between both of them. For Loop in Programming:The for loop is used when you know in advance how many times you want
4 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
Difference between For Loop and While Loop in Programming
Both for loops and while loops are control flow structures in programming that allow you to repeatedly execute a block of code. However, they differ in their syntax and use cases. It is important for a beginner to know the key differences between both of them. For Loop in Programming:The for loop is used when you know in advance how many times you
3 min read
Difference between While Loop and Do While Loop in Programming
While loop and Do while loop concepts are fundamental to control flow in programming, allowing developers to create loops that repeat a block of code based on certain conditions. The choice between "while" and "do while" depends on the specific requirements of the program and the desired behavior of the loop. It is important for a beginner to know
4 min read
A nested loop puzzle
Which of the following two code segments is faster? Assume that compiler makes no optimizations. C/C++ Code /* FIRST */ for(i = 0; i < 10; i++) for(j = 0; j < 100; j++) //do something // This code is contributed by Shubham Singh C/C++ Code /* FIRST */ for(i=0;i<10;i++) for(j=0;j<100;j++) //do something Java Code /* First */ for(i = 0; i
7 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
HTML DOM Video loop Property
The Video loop property is used for setting or returning whether a video should start playing over again when it is finished or not. Syntax: Returning the loop property:videoObject.loopSetting the loop property:videoObject.loop = true|false Property Values: true | false: It is used to specify whether the video should start playing over again, every
2 min read
Print first m multiples of n without using any loop in Python
Given n and m, print first m multiples of a m number without using any loops in Python. Examples: Input : n = 2, m = 3 Output : 2 4 6 Input : n = 3, m = 4 Output : 3 6 9 12 We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array
3 min read
Print 1 to 100 without loop using Goto and Recursive-main
Our task is to print all numbers from 1 to 100 without using a loop. There are many ways to print numbers from 1 to 100 without using a loop. Two of them are the goto statement and the recursive main. Print numbers from 1 to 100 Using Goto statement Follow the steps mentioned below to implement the goto statement: declare variable i of value 0decla
5 min read
Make a loop at k-th position in a linked list
Given a linked list and a position k. Make a loop at k-th position Examples: Input : Given linked list Output : Modified linked list Algorithm: Traverse the first linked list till k-th point Make backup of the k-th node Traverse the linked list till end Attach the last node with k-th node Implementation: C/C++ Code // CPP program for making loop at
8 min read
Print a character n times without using loop, recursion or goto in C++
Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion, and goto. Examples : Input : n = 10, c = 'a'Output : aaaaaaaaaa Input : n = 6, character = '@'Output : @@@@@@ In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While d
2 min read
PHP | Separate odd and even elements from array without using loop
You are given an array of n elements in PHP. You have to separate the elements from the array based on the elements are odd or even. That is, print odd array and even array separately without traversing the original array or using any loop. Examples: Input : array(2, 5, 6, 3, 0) Output : Odd array: 5 , 3 Even array: 2, 6, 0 Input : $input = array(0
3 min read
Synchronous Data Link Control (SDLC) Loop Operation
Loop configuration is basically a communication link that is used to transmit data or information from one link station to another link station conferring the entire loop. At transmit port of the primary station, link connection gets initiated, connects one or more than one secondary station in a serial fashion, and after then ends back at the rece
3 min read
How to Use for Each Loop in Excel VBA?
A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to
3 min read
R - Repeat loop
Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found. Repeat loop, unlike other loops, doesn't use a condition to exit the loop instead it looks for a break statement that executes if a condition within the loop body results to be true.
2 min read
Compiler Design | Detection of a Loop in Three Address Code
Prerequisite - Three address code in Compiler Loop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent actually inside the loop for an iterative program. In the case of the recursive program a block will be ther
3 min read
Why are elementwise additions much faster in separate loops than in a combined loop?
When adding more than 2 arrays, separate loops for adding elements step by step prove to give a better performance than adding the elements in a single loop. To Test the above statement, two code blocks add the 4 array elements namely array a with b and c with d. The first code block uses a combined loop to add them while the second block uses two
3 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Printing all subsets of {1,2,3,...n} without using array or loop
Given a natural number n, print all the subsets of the set [Tex]\{1, 2, 3, ..., n\} [/Tex]without using any array or loop (only the use of recursion is allowed).Examples: Input : n = 4 Output : { 1 2 3 4 } { 1 2 3 } { 1 2 4 } { 1 2 } { 1 3 4 } { 1 3 } { 1 4 } { 1 } { 2 3 4 } { 2 3 } { 2 4 } { 2 } { 3 4 } { 3 } { 4 } { } Input : n = 2 Output : { 1 2
8 min read
C# | foreach Loop
Prerequisite: Loops in C# Looping in a programming language is a way to execute a statement or a set of statements multiple numbers of times depending on the result of a condition to be evaluated. The resulting condition should be true to execute statements within loops. The foreach loop is used to iterate over the elements of the collection. The c
4 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Article Tags :
three90RightbarBannerImg