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.
C++20 introduces std::erase_if
for the very purpose of the objective in this question.
It simplifies the erase-remove idiom for std::vector
, and is also implemented for other standard containers, such as std::map
or std::string
.
Given the example solution in the (previously) accepted answer:
v.erase(std::remove_if(
v.begin(), v.end(),
[](const int& x) {
return x > 10; // put your condition here
}), v.end());
You can now make the same logic more readable as:
std::erase_if( v, [](int x){return x > 10;} );
// container ^ ^ predicate