c++ 列表刪除元素(erase)
阿新 • • 發佈:2018-12-12
#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'; }