How do I iterate safely and efficiently with std::set?

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; }

C++ std::set iteration iterators range-based for loop unique elements safe iteration