std::back_inserter
only works for container with push_back
, so it won't work for set
and map
On the other hand, std::inserter
works for all container types. So can I always use std::inserter(container, container.end())
?
So is the following code good for all kind of container types?
template <class TContainer, class TElement>
TContainer create(TElement element)
{
TContainer container;
auto inserter = std::inserter(container, container.end());
for (int i = 0; i < some_number; ++i)
{
element = do_something(element);
if (condition)
{
*inserter++ = element;
}
}
return container;
}
// use like
create<std::vector<int>>(1);
create<std::set<int>>(1);
It will work with the exception that standard class std::forward_list
has no method insert
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With