Open In App

How to Traverse Set using for_each Loop in C++?

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, STL provides a for_each algorithm which works as a loop for the given range and implements the given function for each element in the range. In this article, we will learn how to use a for_each loop with a set in C++ STL.

Traverse Set using for_each Loop in C++

To traverse a set using a for_each loop in C++ STL, we will need a callable function that prints the elements of the set. We can define this callable as a functor, lambda expression, and also a normal function. This function will be applied to all the elements of the set.

Syntax of for_each Loop

for_each (InputIterator start_iter, InputIterator last_iter, Function fnc)

here,

  • start_iter: The beginning position from where function operations have to be executed.
  • last_iter: The ending position till where function has to be executed.
  • fnc/obj_fnc: The 3rd argument is a function or an object function whose operation would be applied to each element.

C++ Program to Use a for_each Loop with a Set

C++




// C++ Program to use a for_each Loop to traverse a Set
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
  
// Driver Code
int main()
{
    set<int> mySet = { 1, 2, 3, 4, 5 };
  
    // Define a lambda function to print each element
    auto printElement
        = [](int element) { cout << element << " "; };
  
    // Use std::for_each to iterate over the set and apply
    // the lambda function to each element
    for_each(mySet.begin(), mySet.end(), printElement);
  
    cout << endl;
  
    return 0;
}


Output

1 2 3 4 5 

Time Complexity: O(N)
Space Complexity: O(1)

We can use the for_each loop for any task that we can do with other types of loops.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads