#include #include #include using namespace std; int main() { list li {0, 10, 20, 30, 40}; //born holding 5 ints //Simplest way to loop through a list: for (auto i: li) { cout << i << "\n"; } cout << "\n"; //We can loop through a list using an iterator like we loop through an //array using a pointer. //The iterator can be dereferenced with *, and incremented with ++. for (auto it {begin(li)}; it != end(li); ++it) { cout << *it << "\n"; } cout << "\n"; //Loop through an array using a pointer. p is an int *p; int a[] {50, 60, 70, 80, 90}; for (auto p {begin(a)}; p != end(a); ++p) { cout << *p << "\n"; } cout << "\n"; /* //Doesn't work: we can't increment an iterator that points to an element //that has been erased. for (auto it {begin(li)}; it != end(li); ++it) { if (*it == 20) { li.erase(it); } } */ //One way to make it work: for (auto it {begin(li)}; it != end(li);) { const bool deservesToDie {*it == 20}; ++it; if (deservesToDie) { li.remove(20); //Remove every 20 } } //Make sure the 20 was removed. for (auto i: li) { cout << i << "\n"; } return EXIT_SUCCESS; }