Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
c++

How to use the for_each() function in C++

Vinisha Maheshwari

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.

Parameters

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.

Return value

This function has no return value.

Code

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;
}

Using for_each() function in C++

Explanation

  • In lines 1 and 2, we import the required header file.
  • In lines 5 to 8, we define a function to pass it as an argument for operational purpose on each element.
  • In line 11, we make a main function.
  • In line 13, we declare an array of int data type of size = 7.
  • In lines 14 and 15, we display some messages regarding the result.
  • In line 16, we use the 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++.

RELATED TAGS

communitycreator
c++
RELATED COURSES

View all Courses

Keep Exploring