C++ std::back_inserter 用于 std::set?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/908272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:54:50  来源:igfitidea点击:

std::back_inserter for a std::set?

c++algorithmstl

提问by rlbond

I guess this is a simple question. I need to do something like this:

我想这是一个简单的问题。我需要做这样的事情:

std::set<int> s1, s2;
s1 = getAnExcitingSet();
std::transform(s1.begin(), s1.end(), std::back_inserter(s2), ExcitingUnaryFunctor());

Of course, std::back_inserterdoesn't work since there's no push_back. std::inserteralso needs an iterator? I haven't used std::inserterso I'm not sure what to do.

当然,std::back_inserter不起作用,因为没有push_back. std::inserter还需要迭代器?我没用过std::inserter所以我不知道该怎么做。

Does anyone have an idea?

有没有人有想法?



当然,我的另一个选择是对 使用向量s2s2,然后稍后对其进行排序。也许这样更好?

回答by Johannes Schaub - litb

setdoesn't have push_backbecause the position of an element is determined by the comparator of the set. Use std::inserterand pass it .begin():

set没有,push_back因为元素的位置由集合的比较器决定。使用std::inserter并传递它.begin()

std::set<int> s1, s2;
s1 = getAnExcitingSet();
transform(s1.begin(), s1.end(), 
          std::inserter(s2, s2.begin()), ExcitingUnaryFunctor());

The insert iterator will then call s2.insert(s2.begin(), x)where xis the value passed to the iterator when written to it. The set uses the iterator as a hint where to insert. You could as-well use s2.end().

然后插入迭代器将调用传递给迭代器的值s2.insert(s2.begin(), x)在哪里x写入。该集合使用迭代器作为插入位置的提示。你也可以使用s2.end().

回答by alfC

In 2016 there was a proposal to have a "single argument inserteriterator". https://isocpp.org/files/papers/p0471r0.html. I couldn't find if it the proposal advanced. I think it makes sense.

2016 年,有人提议使用“单参数inserter迭代器”。 https://isocpp.org/files/papers/p0471r0.html。我找不到提案是否有进展。我认为这是有道理的。

For now you can have this behavior defining the maker function:

现在,您可以使用以下行为来定义 maker 函数:

template<class Container>
auto sinserter(Container& c){
    using std::end;
    return std::inserter(c, end(c));
}

Used as:

用作:

std::transform(begin(my_vec), end(my_vec), sinserter(my_set), [](auto& e){return e.member;});