i want to remove elements within a container(for now it is unordered_set
) by certain condition
for (auto it = windows.begin(); it != windows.end(); ) {
if ((*it)->closed() == 0)
it = numbers.erase(it);
else
++it;
}
i know the erase(it)
will return the position immediately following the last of the elements erased.
but
Is it mandatory by the standard there won't cause the rearrangement for the iteation when invoking erase
? Is it always safe for all containers and all platforms? Say there may be some magic implementation for certain type of container within certain platform.
The C++ standard requires that unordered_set::erase
preserve the order of remaining elements, and return an iterator immediately following those being erased. Therefore, the loop you show is well-defined.
[unord.req]/14 ... The
erase
members shall invalidate only iterators and references to the erased elements, and preserve the relative order of the elements that are not erased.
[unord.req]/11, Table 91
a.erase(q)
Erases the element pointed to byq
. Returns the iterator immediately followingq
prior to the erasure.