std :: vector删除满足某些条件的元素 [英] std::vector removing elements which fulfill some conditions

查看:97
本文介绍了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的删除习惯用法:

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());

这篇关于std :: vector删除满足某些条件的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆