std::for_each() in C++

In this article, we are going to see what is STL function for_each(), and how to use that efficiently in programs?
Submitted by Radib Kar, on July 16, 2020

std::for_each()

for_each() is a very useful function which helps to invoke a function fn() on each element in the STL container. This helps actually to write code in short and to reduce size of our codebase.

Below is the syntax for the for_each(),

Syntax:

for_each(
    InputIterator first, 
    InputIterator last, 
    Function fn);

Where,

  • InputIterator first = starting of the container
  • InputIterator last = end of the container
  • Function fn = function to be invoked on each element of container

Below are examples of using for_each() efficiently.

1) Printing all elements

For each can be used to print elements in any container. Below is the example where we have printed a vector and map to understand the usage.

#include <bits/stdc++.h>
using namespace std;

void myfunc1(int i)
{
    cout << i << " ";
}

void myfunc2(pair<char, int> p)
{ //ecah element of a map is pair
    cout << p.first << "->" << p.second << endl;
}

int main()
{
    vector<int> arr{ 3, 4, 2, 6, 5, 1 };
 
    map<char, int> mymap;
 
    mymap['a'] = 3;
    mymap['c'] = 3;
    mymap['b'] = 6;
    mymap['d'] = 4;
    mymap['e'] = 2;
    mymap['f'] = 1;

    cout << "Printing the vector\n";
    for_each(arr.begin(), arr.end(), myfunc1);
    cout << "\n";
 
    cout << "Printing the map\n";
    for_each(mymap.begin(), mymap.end(), myfunc2);
    cout << "\n";
    
    return 0;
}

Output:

Printing the vector
3 4 2 6 5 1
Printing the map
a->3
b->6
c->3
d->4
e->2
f->1

2) Replace the vowels with '*'

In this example, we will see how to update the elements of the container. We can update by passing a reference to the elements and updates within the function. In an early article, we saw how to replace vowels using find_first_of(). In the below program we have replaced all the vowels using for_each() which is more efficient and takes only O(n).

#include <bits/stdc++.h>
using namespace std;

void myfunc(char& c)
{ //to update reference is passed

    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'o')
        c = '*';
}

int main()
{
    string str = "includehelp";
    
    cout << "Initially string is: " << str << endl;
    for_each(str.begin(), str.end(), myfunc);
    cout << "After updation\n";
    cout << str << endl;
    
    return 0;
}

Output:

Initially string is: includehelp
After updation
*nclud*h*lp

So, the advantage of using for_each() is it reduces the codebase size and makes the code product level. Also, the time complexity is O(n). If there is any case, where each and every element undergoes huge processing with a large codebase you can use for_each().





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.