C++

C++ std:: for_each() loop

“The std::for-each loops are a different capability that serves the same goal as general looping techniques like “for,” “while,” and “do-while” that are supported by the C++ language. This loop takes a function that runs through each element of the container before returning. For this loop to work, it must be included because it is specified in the header file “algorithm”: #include <algorithm> whenever you iterate through the elements of an array or container and carry out various operations on them, such as accessing, changing, etc. Although you may get the same result by entering the entire for loop, using this method will save you time, cut the number of program codes, and lower the likelihood of some bugs.”

Syntax of std::for_each() loop in C++

The syntax of std::for each() loop, we deployed in C++ is as follows:

for_each ( begin_iterator, end_iterator, func)

 
Where func is a one-parameter function that takes each item from the range[begin, end] as an argument, and begins and end are the input iterators referring to the starting and finishing points of the region in the sequence to evaluate. Below, we have explained the functionality of each parameter.

begin_iterator: an input iterator referring to the first position in the sequence we are using for evaluation that begins the range.

end_iterator: an input iterator refers to the range’s end in the evaluation sequence we are using.

func: a function with one argument that takes each component of the range [start, end] as an argument. The function’s parameter may be supplied either “by-reference” or “by-value.” This function might or might not produce a result.

Example 1

Let’s look at a straightforward example where we use the std::for each() function to output every element inside the range [start, end].

#include<iostream>
#include<algorithm>
#include<array>

void Display_item(int item){
    std::cout<<item<<" ";
}
int main(){
    std::array<int,9> int_array = {2,4,6,-6,0,110,-2,77};
    std::cout<<"Displaying the items: \n";
    std::for_each(int_array.begin(),int_array.end(),Display_item);  
    return 0;
}

 

The code begins from the header section. We have three header files of C++. For utilizing the std::for_each loop, we have added the algorithm header file. Then, we have created the void function as Display_item, which takes an input item of data type int. Inside that function, we have just the std::cout command for this item variable.

Next, we have the main function where we have declared and initialized an array. The std::for_each loop is used to cycle over each element in the given array. The Display_item function is called to display the array of elements within the range [begin, end] for only one time.

Example 2

Utilizing std::for each to make persistent alterations to the collection. The provided function takes the parameters “by-reference” to modify the collection’s elements permanently.

#include<iostream>
#include<algorithm>
#include<array>  
void func_uppercase(std::string &str_val){
    for(int i=0;i<str_val.length();i++){
        if(str_val[i] >= 'a' and str_val[i] <= 'z'){
            str_val[i] = (char)(str_val[i]-'a' + 'A');
        }
    }
}
int main(){
    std::cout<<"output: \n";
    std::array<std::string,4> str_array = {"the","program","of",
    "c++"};
    std::for_each(str_array.begin(),str_array.end(),func_uppercase);
    for(int i=0; i<str_array.size(); i++){
        std::cout<<str_array[i]<<" ";
    }
    return 0;
}

 

Here in the initial step, we have imported the header files for the implementation of the program. After that, we constructed a function func_uppercase for transforming the lower-case string to the upper-case string. Then, we deployed the main method where we defined an array of strings that has all the lower case. The std::for_each loop is used to iterate over all the string characters. The std::for_each loop invokes the func_uppercase function as an argument for each string character in the range[begin, end]. After that, we have a for loop for printing all the string characters after the conversion in the upper case.

You can visualize in the output screen that all the lowercase string characters are transformed into uppercase.

Example 3

The example that follows employs a lambda function to increase each member in a vector before computing their sum using an overloaded operator() in a function’s object, also known as a functor.

#include <vector>
#include <algorithm>
#include <iostream>
 
struct Add {
    Add() { add = 0; }
    void operator()(int n) { add += n; }
 
    int add;
};

int main()
{
    std::vector<int> numbers{4, 5, 1, 8, 16, 221};
 
    std::cout << "Numbers before: ";
    for (auto n : numbers) {
        std::cout << n << " ";
    }
    std::cout << '\n';
    std::for_each(numbers.begin(),numbers.end(),[](int &n){ n++; });
    Add a = std::for_each(numbers.begin(), numbers.end(), Add());
 
    std::cout << "Numbers after:  ";
    for (auto n : numbers) {
        std::cout << n << " ";
    }
    std::cout << '\n';
    std::cout << "Result: " << a.add << '\n';
}

 

Here, we have established a structure and assigned a name Add. The function Add() is also defined there, and inside that function, we initialize the variable add with the number zero. Also, the void function is created with the name operator, which increments the value of n. Then comes the main method of this program.

Inside the main method, we have declared the vector class where we have initialized the list of random numbers. We have printed the numbers by using the for loop. After that, we have std::for_each loop for the iteration over each element in the number list, and then each element in the list is incremented. We have printed the numbers after the for_each loop operation. In the end, we have displayed the sum of the numbers by creating the object as a by invoking the add variable.

The numbers are generated before and after the for_each loop as an output. Also, the sum of the numbers is displayed below.

Example 4

Element printing in any container is possible with the std::for_each function. To understand how to use it, see the example where we printed a vector and a map below.

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

void function_1(int i)
{
    cout << i << " ";
}
void function_2(pair<char, int> p1)
{
    cout << p1.first << "->" << p1.second << endl;
}

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

    cout << "Displaying the vector\n";
    for_each(array.begin(), array.end(), function_1);
    cout << "\n";
 
    cout << "Displaying the map\n";
    for_each(map_val.begin(), map_val.end(), function_2);
    cout << "\n";
   
    return 0;
}

 

We have defined the function as function_1 where the variable “i” is declared, and inside that function, we have displayed the “i” with the cout command. Then, we constructed another function as function_2, which is called the pair class, and set the object p. Inside the function_2, we have defined each element in a pair for the map. Then, within the main function, we initialize an array of vectors and also map values. Then, we utilize the for_each loop for the vectors and the maps for iteration on each element.

The execution of the above program generated the following output.

Conclusion

Therefore, utilizing std::for_each() has the benefit of making the program product level and shrinking the size of the codebase. Additionally, O(n) is the temporal complexity. You can use std:: for_each() in any situation when every element must go through a lot of processing and has a large codebase. The more flexible std::for_each(). Any sort of container can be used with iteration. On top of std::for_each(), it enables us to create an algorithm that operates with an iterator.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.