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

Iterating through an `std::unordered_set` in C++ safely and efficiently can be done using different methods depending on the context. Here are some common approaches:

  • Range-based For Loop: The simplest and most readable way to iterate through an `unordered_set`.
  • Iterator-Based For Loop: Using iterators gives you more control, allowing you to modify the set during iteration.
  • Copying to a Vector: If you need to modify the set while iterating, copy the elements into a vector first.

Example of Iterating through std::unordered_set

#include <iostream> #include <unordered_set> int main() { std::unordered_set<int> mySet = {1, 2, 3, 4, 5}; // Range-based for loop for (const auto& element : mySet) { std::cout << element << " "; } std::cout << std::endl; // Iterator-based for loop for (auto it = mySet.begin(); it != mySet.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; return 0; }

C++ std::unordered_set iteration range-based for loop iterator