Erasing Elements while Iterating

Is it safe to erase elements from a std::unordered_set while iterating over it?

Erasing elements from a std::unordered_set while iterating over it can lead to undefined behavior. The iterator can become invalidated after an erase operation, causing issues if you continue to use it.

However, std::unordered_set provides a safe way to erase elements during iteration using the return value of the erase() method:

#include <iostream>
#include <unordered_set>

int main() {
  std::unordered_set<int> Numbers{1, 2, 3, 4, 5};

  auto it = Numbers.begin();
  while (it != Numbers.end()) {
    if (*it % 2 == 0) {
      it = Numbers.erase(it);  
    } else {
      ++it;
    }
  }

  for (int Num : Numbers) {
    std::cout << Num << " ";
  }
}
1 3 5

When erasing an element, erase() returns an iterator to the next element in the container. By assigning the return value of erase() back to the iterator, we ensure that the iterator remains valid and points to the next element after the erased one.

In the example above, we safely erase all even numbers from the set while iterating over it. The odd numbers remain in the set, as seen in the output.

Hash Sets using std::unordered_set

This lesson provides a thorough understanding of std::unordered_set, from basic initialization to handling custom types and collisions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Implementing a Custom Hash Function
How can I implement a custom hash function for my user-defined type to use with std::unordered_set?
Using a Custom Allocator with std::unordered_set
How can I use a custom allocator with std::unordered_set?
Difference between rehash() and reserve()
What is the difference between rehash() and reserve() in std::unordered_set?
Using std::unordered_set with Smart Pointers
How can I store smart pointers like std::unique_ptr in a std::unordered_set?
Checking if a Key Exists without Inserting
How can I check if a key exists in a std::unordered_set without inserting it if it doesn't?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant