Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I always use std::inserter(container, container.end()) instead of std::back_inserter(container)?

Tags:

c++

c++11

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);
like image 251
Bryan Chen Avatar asked Apr 29 '14 09:04

Bryan Chen


1 Answers

It will work with the exception that standard class std::forward_list has no method insert

like image 143
Vlad from Moscow Avatar answered Sep 21 '22 21:09

Vlad from Moscow