diff --git a/lectures/09_iterators_linked_lists/README.md b/lectures/09_iterators_linked_lists/README.md index b186957..0af17b2 100644 --- a/lectures/09_iterators_linked_lists/README.md +++ b/lectures/09_iterators_linked_lists/README.md @@ -415,6 +415,34 @@ p = s.erase(p); Even though the erase function has the same syntax for vectors and for list, the vector version is O(n), whereas the list version is O(1). Play this [animation](https://jidongxiao.github.io/CSCI1200-DataStructures/animations/lists/iterator/index.html) to see why. +Here is an [example program](list_erase.cpp) demonstrating the usage of safely erasing elements from an std::list while iterating over it. + +```cpp +#include +#include + +int main() { + std::list numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + // iterate over the list and remove even numbers + for (std::list::iterator it = numbers.begin(); it != numbers.end(); ) { + if (*it % 2 == 0) { // if the element is even + it = numbers.erase(it); // erase returns the next valid iterator + } else { + ++it; // move to the next element + } + } + + // print the modified list + // range based for loop: all STL containers that provide begin() and end() member functions support range-based for loops (introduced in C++11). + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + return 0; +} +``` + ## 9.10 Insert - Similarly, there is an insert function for STL lists that takes an iterator and a value and adds a link in the diff --git a/lectures/09_iterators_linked_lists/list_erase.cpp b/lectures/09_iterators_linked_lists/list_erase.cpp new file mode 100644 index 0000000..9c366c5 --- /dev/null +++ b/lectures/09_iterators_linked_lists/list_erase.cpp @@ -0,0 +1,23 @@ +#include +#include + +int main() { + std::list numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + // iterate over the list and remove even numbers + for (std::list::iterator it = numbers.begin(); it != numbers.end(); ) { + if (*it % 2 == 0) { // if the element is even + it = numbers.erase(it); // erase returns the next valid iterator + } else { + ++it; // move to the next element + } + } + + // print the modified list + // range based for loop: all STL containers that provide begin() and end() member functions support range-based for loops (introduced in C++11). + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + return 0; +}