使用 std::remove_if 跟踪已删除的元素 [英] Keeping track of removed elements using std::remove_if

查看:24
本文介绍了使用 std::remove_if 跟踪已删除的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 vector 中删除一些元素,并且正在使用 remove_if 算法来做到这一点.但是我想跟踪删除的元素,以便以后可以对它们执行一些操作.我用下面的代码试过这个:

I want to remove some elements from a vector and am using remove_if algorithm to do this. But I want to keep track of the removed elements so that I can perform some operation on them later. I tried this with the following code:

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;


struct IsEven
{
    bool operator()(int n) 
    {
        if(n % 2 == 0)
        {
            evens.push_back(n);
            return true;
        }

        return false;
    }

    vector<int> evens;
};

int main(int argc, char **argv)
{

    vector<int> v;
    for(int i = 0; i < 10; ++i)
    {
        v.push_back(i);
    }

    IsEven f;
    vector<int>::iterator newEnd = remove_if(v.begin(), v.end(), f);
    for(vector<int>::iterator it = f.evens.begin(); it != f.evens.end(); ++it)
    {
        cout<<*it<<"\n";
    }

    v.erase(newEnd, v.end());

    return 0;
}

但这不起作用,因为 remove_if 接受我的函子对象的copy,所以存储的 evens 向量是不可访问的.实现这一目标的正确方法是什么?

But this doesn't work as remove_if accepts the copy of my functor object, so the the stored evens vector is not accessible. What is the correct way of achieving this?

附言:这个例子,偶数和赔率只是为了举例,我的真实代码有些不同.因此,不要提出一种以不同方式识别偶数或奇数的方法.

P.S. : The example, with even and odds is just for example sake, my real code is somethinf different. So don't suggest a way to identify even or odds differently.

推荐答案

解决方案不是remove_if,而是partial_sort partition.不同的是,remove_if 只保证 [begin, middle) 包含匹配的元素,而 partition 也保证 [middle,end) 包含与谓词不匹配的元素.

The solution is not remove_if, but it's cousin partial_sort partition. The difference is that remove_if only guarantees that [begin, middle) contains the matching elements, but partition also guarantees that [middle, end) contains the elements which didn't match the predicate.

因此,您的示例变得只是(请注意,不再需要 evens):

So, your example becomes just (note that evens is no longer needed):

vector<int>::iterator newEnd = partition(v.begin(), v.end(), f);
for(vector<int>::iterator it = newEnd; it != v.end(); ++it)
{
    cout<<*it<<"\n";
}
v.erase(newEnd, v.end());

这篇关于使用 std::remove_if 跟踪已删除的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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