for_each loop in C++ Last Updated : 12 Jul, 2021 Comments Improve Suggest changes Like Article Like Report 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 loopIt makes code more readablefor_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; } OutputUsing 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 ; } } OutputUsing 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; } Output2 3 4 5 6 Comment More infoAdvertise with us A Astha Tyagi Improve Article Tags : C++ Practice Tags : CPP Similar Reads C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why 5 min read Setting up C++ Development Environment C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro 8 min read Writing First C++ Program - Hello World Example The "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu 4 min read C++ Variables In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable 4 min read C++ Data Types Data types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ 7 min read Operators in C++ C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu 9 min read Basic Input / Output in C++ In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes 5 min read Decision Making in C++Decision Making in C (if , if..else, Nested if, if-else-if )In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n 7 min read C++ if StatementThe C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { int 3 min read C++ if else StatementThe if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec 3 min read C++ if else if LadderIn C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I 3 min read C++ Nested if-else StatementNested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else statements when we want to implement multilayer conditions (condition inside the condition inside the condition and so on). C++ allows any number of nesting levels.Let's tak 3 min read Switch Statement in C++In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is an alternative to the long if-else-if ladder which provides an easy way to execute different parts of code based on the value of the e 5 min read Jump statements in C++Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.In C++, there is four jump statement:Table of Contentcontinue Statementbreak Statementreturn Statementgoto S 4 min read C++ LoopsC++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int 7 min read 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 given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand.Let's take a look at an example:C++#include <bits/stdc++.h 6 min read C++ While LoopIn C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate 3 min read C++ do while LoopIn C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the 4 min read Range-Based for Loop in C++In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.Let's take 3 min read Functions in C++ A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the 9 min read Like