for_each: Apply a function to a range of elements in C++
Satyam Lachhwani
Posted on October 14, 2021
There are times when we need to apply a function to a range of elements in the container and C++ provides us with a native way to do it.
Let's first see it in action before going into details:
std::vector<int> nums{1, 34, 23, 3, 18};
auto print = [](const int& n) { std::cout << " " << n; };
std::for_each(nums.begin(), nums.end(), print);
As you can see, we have used lambda expressions in the above example but we can also use function in the same place. Let me show it to you.
void printFunc(int &n) {
std::cout<<n<<" ";
}
int main()
{
std::vector<int> nums{1, 34, 23, 3, 18};
std::for_each(nums.begin(), nums.end(), printFunc);
}
Makes sense, right? π
Use:
Include the required header file in order to be able to use for_each function. You can either include bits/stdc++.h or include algorithm on the top of your .cpp file.
Syntax:
for_each(startIterator, endInterator, functionExpression);
Parameters:
π startIterator - Starting address of the container.
π endIterator - Ending address (range up to which the elements would be examined)
π functionExpression - A function that would be applied to the members of the container in given range.
The signature of the function should be equivalent to the following:
void fun(const Type &a);
Another example:
Suppose, we want to get initials of name from a list of names, we can write a function to do it for a string and pass it to the third parameter to for_each. Although this can also be done by iterating through the container and applying the function to each element of container but this is a syntactic sugar on top of it.
void retrieveNameInitials(string &str) {
istringstream ss(str);
str = "";
string word;
while (ss >> word)
str += word[0];
}
int main()
{
std::vector<string> names{"Rahul Singh", "Rohan Kumar", "Ayush Ratre", "John Doe"};
std::for_each(names.begin(), names.end(), retrieveNameInitials);
for(auto i:names) cout<<i<<" ";
}
// outputs: RS RK AR JD
If we want to apply the function to not all elements but some in the range, we can pass the addresses accordingly.
for_each(container.begin() + 1, container.begin() + 5, functionExpression);
The above line will apply the function to elements from position 1 to 4 (end address is not inclusive) in the container, given that second parameter doesn't exceed end of container.
For full reference and more examples, visit here
If you find anything wrong or if you know some more exciting functions or other stuff related to C++, please drop a comment below so we learn together.
My Profile -
Posted on October 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.