How to Iterate Over Set in C++: Simple Examples and Tips
To iterate over a
std::set in C++, you can use a range-based for loop or iterators. The range-based loop is simple and reads each element in ascending order automatically.Syntax
You can iterate over a std::set using either a range-based for loop or explicit iterators.
- Range-based for loop: Automatically loops through each element.
- Iterator loop: Uses
begin()andend()to access elements manually.
cpp
std::set<int> mySet = {1, 2, 3}; // Range-based for loop for (const auto& element : mySet) { // use element } // Iterator loop for (auto it = mySet.begin(); it != mySet.end(); ++it) { // use *it }
Example
This example shows how to create a std::set of integers and print each element using a range-based for loop.
cpp
#include <iostream> #include <set> int main() { std::set<int> numbers = {10, 5, 20, 15}; for (const auto& num : numbers) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Output
5 10 15 20
Common Pitfalls
Common mistakes when iterating over a std::set include:
- Trying to modify elements directly (sets are ordered and elements are const).
- Using a loop that modifies the set while iterating, which invalidates iterators.
- Assuming the order is insertion order;
std::setalways sorts elements.
cpp
/* Wrong: Trying to modify elements in set */ std::set<int> s = {1, 2, 3}; for (auto& x : s) { // x = x + 1; // Error: elements are const } /* Correct: Create a new set or copy elements if modification needed */ std::set<int> s2; for (const auto& x : s) { s2.insert(x + 1); }
Quick Reference
Tips for iterating over std::set:
- Use range-based for loops for simplicity.
- Remember elements are sorted automatically.
- Do not modify elements in place.
- Use iterators if you need more control.
Key Takeaways
Use range-based for loops to iterate over std::set easily and clearly.
Elements in std::set are always sorted in ascending order.
You cannot modify elements directly inside a std::set during iteration.
Use iterators when you need manual control over the iteration process.
Avoid changing the set while iterating to prevent iterator invalidation.