std::vector removing elements which fulfill some c

2019-01-18 10:44发布

问题:

As the title says I want to remove/merge objects in a vector which fulfill specific conditions. I mean I know how to remove integers from a vector which have the value 99 for instance.

The remove idiom by Scott Meyers:

vector<int> v;
v.erase(remove(v.begin(), v.end(), 99), v.end());

But suppose if have a vector of objects which contains a delay member variable. And now I want to eliminate all objects which delays differs only less than a specific threshold and want to combine/merge them to one object.

The result of the process should be a vector of objects where the difference of all delays should be at least the specified threshold.

回答1:

std::remove_if comes to the rescue!

99 would be replaced by UnaryPredicate that would filter your delays, which I am going to use a lambda function for.

And here's the example:

v.erase(std::remove_if(
    v.begin(), v.end(),
    [](const int& x) { 
        return x > 10; // put your condition here
    }), v.end());


回答2:

Using predicate function (idiomatic way in C++11):

v.erase(remove_if(
            v.begin(), v.end(), bind(greater<int>(), _1, 99)),
        v.end());


标签: c++ vector stl