In this shot, we discuss how to use the for_each()
function in C++.
The for_each()
function is available in the <algorithm>
header file in C++. It is used as a loop in the code to iterate and perform operations on each element.
The for_each()
function takes the following parameters:
Begin
: The position where the iteration needs to start.End
: The end position where the iteration needs to be performed.Function/Object function
: The function whose operations are performed on each element.This function has no return value.
Let’s take a look at the code snippet below.
#include<iostream>#include<algorithm>using namespace std;void multiply_by_8(int a){cout << a * 8 << " ";}int main(){int arr[7] = { 1, 7, 2, 6, 3, 9, 4 };cout << "Using the for_each(): " << endl;cout << "Multiple of 2 of elements are : ";for_each(arr, arr+4, multiply_by_8);cout << endl;}
main
function.int
data type of size = 7.for_each()
function to perform some operations on each element. We use a function as an argument from the start position to the end position and display them as a result.In this way, we can use the for_each()
function in C++.