简体   繁体   中英

Result of invalid iterator passed to std::unordered_set::erase()

std::unordered_set::erase() has 3 overloads: In the one taking a reference, passing an "invalid" value, ie one that doesn't exist in the set, simply makes erase() return 0. But what about the other two overloads?

Does the C++11 standard say what erase() should do in this case, or it's compiler dependent? Is it supposed to return end() or undefined behavior?

I couldn't find an answer in the specification, cppreference.com, cplusplus.com. On IBM site they say it returns end() if no element remains after the operation, but what happens if the operation itself fails due to an invalid iterator?

And in general, do erase() methods for STL containers simply have undefined behavior in these case? (so I need to check my iterators before I pass any to erase(), or use the unordered_set::erase() overload which takes a value_type reference, which would simply return 0 if it fails)

There is a big semantic difference between trying to remove a value that doesn't occur in set and trying to erase from a invalid iterator.

Trying to use an invalid iterator is undefined behaviour and will end badly.

Do you have a specific use-case you are thinking of when you might want to erase an invalid iterator?

These are two completely different cases. There is no "invalid value", values that don't exist in the set are still valid. So you pass a valid value that s not contained in the set and thus get 0 returned - no elements have been erased.

The other overloads are completely different. The standard requires the iterators passed to the erase methods to be "valid and dereferencable" and "a valid iterator range", respectively. Otherwise the behavior is undefined.

So yes, iterators have to be valid. But you cannot check if an iterator is valid programmatically - you have to make sure from your program logic, that they are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM