在调用 std::remove_if 时跟踪任意迭代器/索引

问题描述 投票:0回答:1

我正在迭代一长串数字。 我经常遇到一个满足某些条件的数字(让我们称之为“x”),然后我将它与一堆其他数字一起从列表中删除,这些数字很难提前预测在列表中的位置,并且可以“x”之后和之前。 之后,我需要从“x”之后未删除的第一个数字开始继续迭代。

我尝试使用

std::remove_if
但如果我这样做,我就会忘记需要在哪里恢复迭代。 在这种情况下使用此函数时是否有任何技巧可以保留有关迭代器/索引的信息?

一个简单的例子:

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

int main()
{
    std::vector<int> numbers{3, 2, 7, 9, 11, 4, 5, 10};
    auto i = 3;  // Iterator points to the number 9.
    auto toRemove = std::remove_if(numbers.begin(), numbers.end(), [](int x){ return x % 2 != 0; });  // Some removal criteria with result that is hard to predict in advance.
    // The resulting vector will be {2, 4, 10}.
    //TODO insert magic here
    std::cout << i << std::endl;  // i is still 3 but it should be now 1 (it should point to the number 4 which is the first non-removed after 9)
    numbers.erase(toRemove, numbers.end());
}
c++ stl iterator
1个回答
0
投票

您可以先删除目标之前和之后的元素:

template <typename F>
void filter(std::vector<int>& v, std::size_t& index, F f)
{
    auto it = std::remove_if(v.begin(), v.begin() + index + 1, f);
    v.erase(std::copy_if(std::make_move_iterator(v.begin() + index + 1),
                         std::make_move_iterator(v.end()),
                         it,
                         [&](auto&& e){ return !f(e);}), v.end());
    index = std::distance(v.begin(), it);
}

演示

© www.soinside.com 2019 - 2024. All rights reserved.