从Vector中删除元素同时保持顺序-需要更好的方法
Removing an element from a Vector while preserving order - need a better approach
我正试图从c++中的向量中删除一个元素。在下面的代码中,我从Vector中的数字列表中删除了一个大于10的元素。我使用嵌套循环来执行删除。是否有更好或更简单的方法来做同样的事情?
// removing an element from vector preserving order
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v {3,2,9,82,2,5,4,3,4,6};
for (int i=0; i < v.size(); i++) {
if (v[i] > 10) { // remove element > 10
while (i < v.size()) {
v[i] = v[i+1];
i ++;
}
}
}
v.pop_back();
for (int i=0; i < v.size(); i++) {
cout << v[i] << "|";
}
return 0;
}
您可能需要查看std::remove_if
bool is_higher_than_10(int i) { return i > 10; }
std::remove_if(v.begin(), v.end(), is_higher_than_10);
因为总是有更多的东西要学习,看看克里斯和本杰明林德利的评论和擦除成语(谢谢大家)
v.erase(std::remove_if(v.begin(), v.end(), is_higher_than_10), v.end());
相关文章:
- C++:将控制台输出存储在宏中更好吗
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 初始化具有非默认构造函数的std::数组项的更好方法
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么新的随机库比std::rand()更好
- 寻找一种更好的方法来表示无符号字符数组
- 哪种方法更好,性能明智
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 什么是更好的做法?通过指针或标识符传递类成员?
- 寻求更好地理解标准::访问
- 线程消息传递或更好:在"大师班"中访问其他班级的成员
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 如何更好地检查两个 char 变量是否在一组值中?
- 有没有更好的方法对C++中的三个整数进行排序?
- 什么模板用法在阶乘中更好
- 平面缓冲区可以利用向量中的 0 吗?还是其他小波比哈尔变换更好?
- 我们应该如何使用枚举类进行索引(或者我们应该更好地避免这种情况)?
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 更好的做法是在数组中插入值,然后排序,或者在插入时保持排序顺序
- 从Vector中删除元素同时保持顺序-需要更好的方法