2

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?

Zizheng Tai
  • 6,170
  • 28
  • 79

1 Answers1

3

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

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

eerorika
  • 232,697
  • 12
  • 197
  • 326