DEV Community

Cover image for for_each: Apply a function to a range of elements in C++
Satyam Lachhwani
Satyam Lachhwani

Posted on

for_each: Apply a function to a range of elements in C++

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);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 -

Github
LinkedIn

Top comments (2)

Collapse
 
pgradot profile image
Pierre Gradot

You can either include bits/stdc++.h

NO, you can't.

See stackoverflow.com/questions/318160...

Collapse
 
satyam1203 profile image
Satyam Lachhwani

Hi, I used to think that it is slow that's why some people don't recommend it. I didn't know that it may not work for some.

I'll explore on that.