Hash Sets using std::unordered_set

Erasing Elements while Iterating

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

Abstract art representing computer programming

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 {

  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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved