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>
?
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)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With