How to use one line to populate a set using the elements of this vector that match a certain condition

  • A+
Category:Languages

I have a vector of elements. I want to populate a set using the elements of this vector that match a certain condition. Can I do this using one line, or in any way that is more concise than the below?


// given vector<int> v

set<int> s;
for (const int& i : v)
{
if (/* some condition on i*/)
s.insert(i);
}

For example, something along the line of:

// given vector<int> v

set<int> s;
s.insert(v.filter(/* lambda here*/));

It goes without saying that the v.filter method should return an iterator, not a separate populated vector, for performance reasons.


You can use std::copy_if with a lambda and std::inserter to insert the values into the set. That looks like


std::copy_if(v.begin(), v.end(), std::inserter(s, s.begin()), [](auto val) { return val == some_condition; });

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: