Reputation: 6616
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
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