在循环中使用 erase(it) 对所有容器和平台来说总是安全的吗?

Is using erase(it) in a loop always safe for all containers and platforms?

我想根据特定条件删除容器中的元素(目前是unordered_set

for (auto it = windows.begin(); it != windows.end(); ) {
    if ((*it)->closed() == 0)
        it = numbers.erase(it);
    else
        ++it;
}

我知道 erase(it) 会 return the position immediately following the last of the elements erased.

标准是否强制要求在调用erase时不会导致迭代重排?它对所有容器和所有平台总是安全的吗?假设在某个平台上可能有一些针对特定类型容器的神奇实现。

C++ 标准要求 unordered_set::erase 保留剩余元素的顺序,return 迭代器紧跟在被擦除的元素之后。因此,您显示的循环定义明确。

[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 by q. Returns the iterator immediately following q prior to the erasure.