This post will discuss how to call a function on every element of a vector in C++.

1. Using std::for_each

The standard solution to call a given function on each of the elements in the specified range is using the std::for_each function. Following is a simple example demonstrating the usage of this function:

Download  Run Code

Output:

2 3 4 5 6

 
This is equivalent to the following, which shortens the code with C++11 lambdas.

Download  Run Code

Output:

2 3 4 5 6

2. Using std::transform

Another option is to use the std::transform standard algorithm, which applies a given function to elements of the specified range. It is defined in the header file <algorithm>, and can be invoked as follows:

Download  Run Code

Output:

2 3 4 5 6

 
The following code uses lambda expressions that were introduced with C++11.

Download  Run Code

Output:

2 3 4 5 6

That’s all about calling a function on every element of a vector in C++.