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

时间:2013-03-22 04:10:23

标签: c++ loops vector

我正在尝试从C ++中的Vector中删除一个元素。在下面的代码中,我从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;
}

1 个答案:

答案 0 :(得分:3)

您可能需要查看std::remove_if

bool is_higher_than_10(int i) { return i > 10; }
std::remove_if(v.begin(), v.end(), is_higher_than_10);

因为总有更多要学习,请看看克里斯和本杰明林德利的评论以及Erase-remove idiom(谢谢你们)

v.erase(std::remove_if(v.begin(), v.end(), is_higher_than_10), v.end());
相关问题