I am using remove() of std::list to remove elements in a for loop. But it is creating segmentation fault. I am not using iterators. Program is given below.
#include <iostream>
#include <list>
using namespace std;
int main() {
list <int> li = {1, 2, 3, 4, 5};
for(auto x : li)
{
if (x == 4) {
li.remove(x);
}
}
return 0;
}
In case of iterators, I understand that iterators are invalidated if we remove an element and we need to take care of incrementing iterator properly. But here I am not using iterators and I am using remove() which doesn't return any. Can any one please let me know if we can't use remove in a loop or if there is any issue with the code.
You are mistaken. Range-based
forloops are based on iterators. So after this call:The current used iterator becomes invalid.
For example, in C++17, the range-based
forloop is defined in the following way (9.5.4 The range-based for statement):Pay attention to that. Using the range-based
forloop to call the member functionremove()does not make a great sense, because the function will remove all elements with the given value.If the compiler supports C++20, you can just write: