Remove elements from a list while iterating through it in C++
This post will discuss how to remove elements from a list while iterating inside a loop in C++.
The idea is to iterate the list using iterators and call list::erase on the desired elements. But we can’t directly call the erase() function inside a for-loop since calling it invalidates the iterator. We can handle this in many ways:
1. We can reset the iterator to the next element in the sequence using the return value of erase(). Note that this will only work with C++11 and above.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <list> #include <algorithm> #include <iterator> using namespace std; int main() { list<string> input = { "red", "green", "blue", "gray", "black" }; list<string>::const_iterator itr = input.cbegin(); while (itr != input.cend()) { // remove strings having length 5 if (itr->length() == 5) { itr = input.erase(itr); } else { ++itr; } } copy(input.begin(), input.end(), ostream_iterator<string>(cout, "\n")); return 0; } |
Output:
red
blue
gray
2. We can also decrement the iterator inside the function arguments using the postfix decrement operator. This way, a copy of the iterator is passed to the erase() function, and the actual iterator is incremented.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <list> #include <iterator> using namespace std; int main() { list<string> input = { "red", "green", "blue", "gray", "black" }; for (auto itr = input.cbegin(); itr != input.end(); itr++) { // remove strings having length 5 if (itr->length() == 5) { input.erase(itr--); } } copy(input.begin(), input.end(), ostream_iterator<string>(cout, "\n")); return 0; } |
Output:
red
blue
gray
3. Like the second solution, we can call the erase() function on a copy of the original iterator after advancing the original iterator to the next element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <list> #include <iterator> using namespace std; int main() { list<string> input = { "red", "green", "blue", "gray", "black" }; list<string>::const_iterator itr = input.cbegin(); while (itr != input.cend()) { list<string>::const_iterator curr = itr++; if (curr->length() == 5) { input.erase(curr); } } copy(input.begin(), input.end(), ostream_iterator<string>(cout, "\n")); return 0; } |
Output:
red
blue
gray
That’s all about removing elements from a list while iterating through it in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)