使用 remove_if 按索引从 C++ 向量中删除

2022-01-10 00:00:00 indexing iterator vector c++ remove-if

我们可以在 C++ 中使用 remove_if 根据对元素进行操作的谓词在线性时间内从向量中删除元素.

We can use remove_if in C++ to remove elements from a vector in linear time based on a predicate that operates on the elements.

bool condition(double d) {...}

vector<double> data = ...
std::remove_if (data.begin(), data.end(), condition);

如果我的情况不是取决于值,而是取决于索引怎么办?换句话说,如果我想删除所有奇数索引元素,或者一些任意索引集等?

What if my condition depends not on the values, but on the indices? In other words, if I wanted to remove all the odd-indexed elements, or some arbitrary index set, etc?

bool condition(int index) {//returns whether this index should be removed}

vector<double> data = ...
std::remove_if (data.begin(), data.end(), ???);

推荐答案

您可以使用指针算法来查找 std::remove_if 传递给谓词的特定元素的索引:

You can use pointer arithmetic to find the index of a specific element that std::remove_if passes to the predicate:

std::remove_if(data.begin(), data.end(),
               [&data](const double& d) { return (&d - &*data.begin()) % 2); });

请注意,remove_if 会传递取消引用迭代器的结果,并且根据表 106 - 标准中的迭代器要求,这保证是 reference.

Note that remove_if passes the result of dereferencing an iterator, and that's guaranteed to be a reference per Table 106 - Iterator requirements in the Standard.

相关文章