remove_if使用示例

vector中的remove_if使用:

    remove_if(ivec.begin(), ivec.end(), function)

作用:刪除滿足function函數的元素。實例如下:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool compare(int d)
{
    return d < 30;
}

int main()
{
    int myints[] = { 15, 36, 7, 17, 20, 39, 4, 1 };
    vector<int> ivec(myints, myints + 8);   // 15 36 7 17 20 39 4 1

    ivec.erase(remove_if(ivec.begin(), ivec.end(), compare), ivec.end());    //刪除滿足compare條件的元素

    for (vector<int>::iterator it = ivec.begin(); it != ivec.end(); ++it)
        cout << *it << endl;     //36 39

    return 0;
}

vector初始化,請參考我的博客:
c++ vector(向量)使用方法詳解(順序訪問vector的多種方式)

vector刪除,請參考我的博客:
vector刪除元素

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章