Possible Duplicate:
How to filter items from a std::map?
std::list::erase not working
I have some silly questions regarding remove, erase in std::list.
I have a class defined as:
class CBase
{
public:
CBase(int i): m(i)
{};
int m;
};
then, I set it up as:
list<CBase> ml;
CBase b1(1);
CBase b2(2);
CBase b3(3);
CBase b4(4);
ml.push_back(b1);
ml.push_back(b2);
ml.push_back(b3);
ml.push_back(b4);
I can erase the item which has m==2 by;
for (list<CBase>::iterator it=ml.begin(); it!=ml.end(); ++it)
{
if (it->m == 2)
{
ml.erase(it--);
}
}
// show what we have now:
for (list<CBase>::iterator it=ml.begin(); it!=ml.end(); it++)
{
cout << it->m;
}
But if I do:
for (list<CBase>::iterator it=ml.begin(); it!=ml.end(); it++)
{
if (it->m == 2)
{
ml.erase(it);
it--;
}
}
There will be exception. Why is this?
And if I want to remove b3,
ml.remove(b3);
will not compile. All the examples I found online use list<int>
, and there is no problem calling mylist.remove(3)
, if mylist is list<int>
. How can I make it work?