std::back_inserter for a std::set?

后端 未结 2 1549
梦谈多话
梦谈多话 2020-12-13 05:15

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

std::set s1, s2;
s1 = getAnExcitingSet();
std::transform(s1.begin(), s1.end()         


        
相关标签:
2条回答
  • 2020-12-13 05:52

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

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

    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;});
    
    0 讨论(0)
  • 2020-12-13 06:00

    set doesn't have push_back because the position of an element is determined by the comparator of the set. Use std::inserter and pass it .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 x is 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().

    0 讨论(0)
提交回复
热议问题