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.
- Why to use for_each?
- 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
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.
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.
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
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 email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Foreach in C++ and Java
- C/C++ do while loop with Examples
- C/C++ For loop with Examples
- C/C++ while loop with Examples
- Difference between for and do-while loop in C, C++, Java
- Difference between while and do-while loop in C, C++, Java
- Difference between for and while loop in C, C++, Java
- Range-based for loop in C++
- Print 1 to 100 in C++, without loop and recursion
- How will you print numbers from 1 to 100 without using loop?
- Print pattern using only one loop | Set 1 (Using setw)
- For Loop in Java | Important points
- Different types of range-based for loop iterators in C++
- Reversed Range-based for loop in C++ with Examples
- What happens if loop till Maximum of Signed and Unsigned in C/C++?
- Print a character n times without using loop, recursion or goto in C++
- Print a number 100 times without using loop, recursion and macro expansion in C?