Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::back_inserter for a std::set?

Tags:

c++

algorithm

stl

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_inserter doesn't work since there's no push_back. std::inserter also needs an iterator? I haven't used std::inserter so I'm not sure what to do.

Does anyone have an idea?


Of course, my other option is to use a vector for s2, and then just sort it later. Maybe that's better?
like image 451
rlbond Avatar asked May 25 '09 22:05

rlbond


People also ask

What is std :: Back_inserter?

std::back_inserter A back-insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy ) to instead insert new elements automatically at the end of the container.

What is inserter in c++?

std::inserter constructs an insert iterator that inserts new elements into x in successive locations starting at the position pointed by it. It is defined inside the header file .

How do you use std transform?

std::transform on a range For example, to obtain the keys that a map contains, you can use std::transform the following way: map<int, string> m = { {1,"foo"}, {42, "bar"}, {7, "baz"} }; vector<int> keys; std::transform(m. begin(), m. end(), std::back_inserter(keys), getFirst);

Is std :: find slow?

std::equal_range on bidirectional iterators is extremely slow, because it has to walk step by step through the range. The std::set. find method, on the other hand, uses the tree structure of std::set to find the element really fast. It can, basically, get midpoints of a range really fast.


1 Answers

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().

like image 52
Johannes Schaub - litb Avatar answered Sep 20 '22 13:09

Johannes Schaub - litb