adding erase example

This commit is contained in:
Jidong Xiao
2025-02-11 13:40:10 -05:00
committed by JamesFlare1212
parent 4054554203
commit b34f9cd0af
2 changed files with 51 additions and 0 deletions

View File

@@ -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 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. 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 <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// iterate over the list and remove even numbers
for (std::list<int>::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 ## 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 - Similarly, there is an insert function for STL lists that takes an iterator and a value and adds a link in the

View File

@@ -0,0 +1,23 @@
#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// iterate over the list and remove even numbers
for (std::list<int>::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;
}