I experimented the following code
list<int> a ={1,2};
list<int> b ={3,4};
a.erase(b.begin());
for (auto x:b) cout << x << endl;
Strangely, the program ran fine without any error. What it prints out is 4. I wonder why erase is a member function when the object is already implicit in the iterator.
This invokes undefined behavior, because you’re passing iterator obtained from one container to a function of other container.
aandbare two different containers, they’re not same.Undefined behavior means anything could happen: it may run as expected, or it may not. Neither the language specification nor the compiler gives guarantee that it will work. It is aptly said “undefined behavior”.
What you should do is this:
Or, if you want to remove all elements equal to
value, then you could simply do this:However, if you use
std::vectorwhich you should be using in most cases. It is default container type in C++, and you should usestd::listonly if you’ve strong reason to do so:And if you want to remove all elements equal to
value, then you can apply popular Erase-Remove Idiom as:Note that
std::vectordoesn’t haveremove()member function, that is why you apply this idiom. You can read my answer here which discusses about this in more detail.