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';
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM