Removing by index from a C++ vector using remove_if(使用 remove_if 按索引从 C++ 向量中删除)
问题描述
我们可以在 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.
这篇关于使用 remove_if 按索引从 C++ 向量中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 remove_if 按索引从 C++ 向量中删除


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30