我有一个列表迭代器,它通过一个列表并删除所有偶数.我可以使用list迭代器来打印出数字,但是我不能使用list的remove()并传入dereferenced迭代器.
我注意到当remove()语句生效时,*itr被破坏了吗?有人可以解释一下吗?
#include <iostream>
#include <list>
#define MAX 100
using namespace std;
int main()
{
list<int> listA;
list<int>::iterator itr;
//create list of 0 to 100
for(int i=0; i<=MAX; i++)
listA.push_back(i);
//remove even numbers
for(itr = listA.begin(); itr != listA.end(); ++itr)
{
if ( *itr % 2 == 0 )
{
cout << *itr << endl;
listA.remove(*itr); //comment this line out and it will print properly
}
}
}
Run Code Online (Sandbox Code Playgroud)