Std :: back_inserter for std :: set?

I think 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_inserter does not work, since there is no push_back . std::inserter also need an iterator? I have not used std::inserter , so I'm not sure what to do.

Does anyone have any ideas?




Of course, my other option is to use the vector for s2 , and then just sort it later. Maybe this is better?
+70
c ++ algorithm stl
May 25 '09 at 10:32 a.m.
source share
1 answer

set does not have push_back , because the position of the 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 it was written. The set uses an iterator as a hint where to insert. You can use s2.end() .

+106
May 25 '09 at 22:42
source share



All Articles