迭代过程中删除指定元素

迭代过程中删除指定元素,第1张

迭代过程中删除指定元素 迭代过程中删除指定元素

总结在迭代过程删除list中指定元素的4种方法

方法1
#include 
#include 

using namespace std;

int main() {
    list lst = {1,2,3,4,5};
    auto it = lst.begin();
    while(it != lst.end()) {
        if (*it == 4) {
            it = lst.erase(it);
        } else {
            ++it;
        }
    }

    for (auto i : lst) {
        cout << i << " ";
    }
    cout << endl;
}

方法2
#include 
#include 

using namespace std;

int main() {
    list lst = {1,2,3,4,5};

    lst.remove_if([](int n) {return n == 4;});

    for (auto i : lst) {
        cout << i << " ";
    }
    cout << endl;
}
方法3
#include 
#include 
#include 

using namespace std;

int main() {
    list lst = {1,2,3,4,5};

    lst.erase(std::remove_if(lst.begin(), lst.end(), [](int n) {
        return n == 4;
    }), lst.end());

    for (auto i : lst) {
        cout << i << " ";
    }
    cout << endl;
}
方法4
#include 
#include 

using namespace std;

int main() {
    list lst = {1,2,3,4,5};

    for (auto it = lst.begin(); it != lst.end(); ++it) {
        if (*it == 4) {
            it = lst.erase(it);
            --it;
        }
    }

    for (auto i : lst) {
        cout << i << " ";
    }
    cout << endl;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5665961.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存