![]() |
VOOZH | about |
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.
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.
for_each (InputIterator start_iter, InputIterator last_iter, Function fnc)here,
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.