How to call a function on every element of a vector in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <algorithm> void increment(int &i) { i++; } int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::for_each(v.begin(), v.end(), &increment); for (int i: v) { std::cout << i << ' '; } return 0; } |
Output:
2 3 4 5 6
This is equivalent to the following, which shortens the code with C++11 lambdas.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::for_each(v.begin(), v.end(), [&](int &i){ i++; }); for (int i: v) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <algorithm> int increment(int &i) { return i + 1; } int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::transform(v.begin(), v.end(), v.begin(), &increment); for (int i: v) { std::cout << i << ' '; } return 0; } |
Output:
2 3 4 5 6
The following code uses lambda expressions that were introduced with C++11.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::transform(v.begin(), v.end(), v.begin(), [&](int &i){ return i + 1; }); for (int i: v) { std::cout << i << ' '; } return 0; } |
Output:
2 3 4 5 6
That’s all about calling a function on every element of a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)