Is there an insert iterator in std::
for unordered sets? As far as I can see, std::inserter
requires an iterator argument. This is unsafe for unordered containers (at least for boost::unordered_set
), because they may reallocate during an insert
operation and render the passed .begin()
iterator invalid.
So currently I have to pass my own iterator which essentially is an boost::function_output_iterator
with a functor that simply calls unorderedSet.insert(param1)
.
Why is it that std::inserter
even requires the hint
iterator argument anyway?
There isn't. The reason that the
hint
argument is required is thatstd::inserter
is meant for containers where position is required in the context of insertion. As you know, this is not the case for unordered containers.vector
in an example of a container where knowingposition
is a requirement for insertion. From cppreference:I know this isn't the answer you're looking for, but rolling out your own is easy enough, if not a bit verbose:
This probably can be refactored to support other kinds of insertion, but I think this is enough for now.
Here's me playing a bit with it:
Live on Godbolt
A thing to note here is that your assertion that passing this
hint
argument to unordered containers is unsafe is wrong. Whenoperator=
is called, and a new element is inserted into the container, theiter
member is updated to whateverinsert
returns. Since this value is required to be valid, there's no way thatiter
can ever be invalidated.