我可以总是使用std :: inserter(container,container.end())而不是std :: back_inserter(container)? [英] Can I always use std::inserter(container, container.end()) instead of std::back_inserter(container)?

查看:136
本文介绍了我可以总是使用std :: inserter(container,container.end())而不是std :: back_inserter(container)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: back_inserter 仅适用于 push_back 的容器,因此它不适用于 set map

std::back_inserter only works for container with push_back, so it won't work for set and map

另一方面, std :: inserter 适用于所有容器类型。所以,我总是可以使用 std :: inserter(container,container.end())

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);


推荐答案

c $ c> std :: forward_list 没有方法 insert

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

这篇关于我可以总是使用std :: inserter(container,container.end())而不是std :: back_inserter(container)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆