How to Traverse Set using for_each Loop in C++?
Last Updated :
27 Feb, 2024
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++
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 1, 2, 3, 4, 5 };
auto printElement
= []( int element) { cout << element << " " ; };
for_each(mySet.begin(), mySet.end(), printElement);
cout << endl;
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...