std::vector 删除满足某些条件的元素
正如标题所说,我想删除/合并满足特定条件的向量中的对象.我的意思是我知道如何从向量中删除整数,例如,其值为 99.
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.
Scott Meyers 的 remove 成语:
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.
推荐答案
std::remove_if代码>来拯救!
99 将被替换为 UnaryPredicate
,它会过滤您的延迟,我将使用 lambda 函数来实现.
99 would be replaced by UnaryPredicate
that would filter your delays, which I am going to use a lambda function for.
这是一个例子:
v.erase(std::remove_if(
v.begin(), v.end(),
[](const int& x) {
return x > 10; // put your condition here
}), v.end());
相关文章