Zizheng Tai
Zizheng Tai

Reputation: 6616

Extracting from set/unordered_set while using iterators

I just learned about the extract function added to std::set/std::unordered_set in C++17. I know this is valid:

while (!my_set.empty()) {
  auto node_handle = my_set.extract(my_set.begin());
  auto elem = std::move(node_handle.value());
}

But is the following safe? (From https://stackoverflow.com/a/42519996/3234803)

for (auto it = my_set.begin(); it != my_set.end(); ) {
  auto node_handle = my_set.extract(it++);
  auto elem = std::move(node_handle.value());
}

I know extract invalidates the iterator passed to it, so extract(it++) saves the next iterator into it before it gets invalidated. But is it guaranteeed that extract doesn't invalidated other iterators?

Upvotes: 6

Views: 836

Answers (1)

eerorika
eerorika

Reputation: 238311

But is it guaranteeed that extract doesn't invalidated other iterators?

Yes. Extract is guaranteed to not invalidate other iterators. Both loops are safe.

Upvotes: 4

Related Questions