Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL way of creating/filling std::set from std::vector

I want to create and fill a set from the contents of a member variable of each entry of a vector. This is what I am doing:

struct S { int i; };

int main()
{
    std::vector<S*> structPtrs;

    // code to fill the above vector

    // create set from the above vector
    std::set<int> setInts;
    for (auto it = structPtrs.begin(); it != structPtrs.end(); ++it)
    {
        setInts.insert((*it)->i);
    }
}

Is there an STL way to do it? Or via any available method(s) in <algorithm>?

like image 520
CinCout Avatar asked Dec 18 '22 00:12

CinCout


1 Answers

You can always apply std::transform from the range defined by the vector onto the "range" defined by an std::inserter:

transform(begin(structPtrs), end(structPtrs),
          inserter(setInts, end(setInts)), [] (S* s) {
  return s->i;
});

That should be more than enough use of the standard library.


If you are willing to look beyond the standard library, there is also the option of using something like boost::transform_iterator, which will allow you to move the range transformation into the set's initialization:

auto transfomer = [](S* s) { return s->i; };
std::set<int> setInts(
  boost::make_transform_iterator(begin(structPtrs), transfomer),
  boost::make_transform_iterator(end(structPtrs), transfomer)
);
like image 128
StoryTeller - Unslander Monica Avatar answered Dec 24 '22 02:12

StoryTeller - Unslander Monica