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.
|
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) { copy(input.begin(), input.end(), ostream_iterator<string>(cout, "\n")); |
Download Run Code
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.
|
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) { copy(input.begin(), input.end(), ostream_iterator<string>(cout, "\n")); |
Download Run Code
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.
|
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) { copy(input.begin(), input.end(), ostream_iterator<string>(cout, "\n")); |
Download Run Code
Output:
red
blue
gray
That’s all about removing elements from a list while iterating through it in C++.
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 🙂
|