Range-Based for Loop with a Set in C++ Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like 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 6Range-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; } OutputElements after iteration: 1 3 4 5 9 Time complexity: O(N log N)Sapce Complexity: O(1) Create Quiz Comment A anuragvbj79 Follow 0 Improve A anuragvbj79 Follow 0 Improve Article Tags : C++ Programs C++ STL cpp-set CPP Examples +1 More Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like