In C++, the std::set
container provides a way to store unique elements following a specific order. When iterating over a std::set
, it's important to do so safely and efficiently to ensure that you don't run into issues, especially if you're modifying the set during iteration.
The most common and efficient way to iterate over a std::set
is to use iterators. You can use a simple for loop along with the begin()
and end()
methods to access each element in the set:
#include <iostream>
#include <set>
int main() {
std::set mySet = {1, 2, 3, 4, 5};
// Safe iteration using iterators
for (std::set::iterator it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << std::endl; // Print each element
}
return 0;
}
Additionally, you can use range-based for loops introduced in C++11 for a more concise syntax:
#include <iostream>
#include <set>
int main() {
std::set mySet = {1, 2, 3, 4, 5};
// Safe iteration using range-based for loop
for (const int& value : mySet) {
std::cout << value << std::endl; // Print each element
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?