VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-traverse-set-using-for_each-loop-in-cpp/

⇱ How to Traverse Set using for_each Loop in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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


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.


Comment
Article Tags: