Open In App

Range-Based for Loop with a Set in C++

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

In C++, a set is a container that stores unique elements in a particular order. A range-based for loop is a feature added in C++11 to iterate over containers. In this article, we will learn how to use a range-based for loop with a set in C++.

Example:

Input:
mySet = {1, 2, 3, 4, 6}

Output:
1 2 3 4 6

Range-Based for Loop with a Set in C++

We can use a range-based for loop with a set in C++ for any operation that can be done using loops. It just requires the name of the set container and iterates each element in the set. In the below program, we have used the range-based for loop to traverse and print the set container.

C++ Program to Traverse a Set using Range-Based for Loop

C++




// C++ Program to show how to use a Range-Based for Loop
// with a Set
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    // Duplicate elements will be ignored
    set<int> mySet = { 3, 1, 4, 1, 5, 9 };
  
    // Iterate over the elements of the set using a
    // range-based for loop
    cout << "Elements of set: " << endl;
    for (const auto& element : mySet) {
        cout << element << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Elements after iteration: 
1 3 4 5 9 

Time complexity: O(N log N)
Sapce Complexity: O(1)


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

Similar Reads