c++ 列表删除元素(erase)

 

#include <list>
#include <iostream>
#include <iterator>
using namespace std;
int main( )
{
    list<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
    c.erase(c.begin());//删除第一个元素
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
    list<int>::iterator range_begin = c.begin();
    list<int>::iterator range_end = c.begin();
    advance(range_begin,2);
    advance(range_end,5);
    c.erase(range_begin, range_end);
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
    // Erase all even numbers (C++11 and later)
    for (auto it = c.begin(); it != c.end(); ) {
        if (*it % 2 == 0) {
            it = c.erase(it);//删除偶数
        } else {
            ++it;
        }
    }
    for (auto &i : c) {
        cout << i << " ";
    }
    cout << '\n';
}

 

posted @ 2018-12-12 20:44  anobscureretreat  阅读(5383)  评论(0编辑  收藏  举报