Search code examples
c++c++11stlstdvectorstdset

Can I insert into a set, all the elements of a vector that matches a condition, in a single line of code


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.


Solution

  • 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; });