从Vector中删除元素同时保持顺序-需要更好的方法

Removing an element from a Vector while preserving order - need a better approach

本文关键字:顺序 更好 方法 Vector 删除 元素      更新时间:2023-10-16

我正试图从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());