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.
Answers to questions are automatically generated and may not have been reviewed.
std::unordered_set
This lesson provides a thorough understanding of std::unordered_set
, from basic initialization to handling custom types and collisions