Click to See Complete Forum and Search --> : why my program can not run correctly?


liuty
April 6th, 2003, 10:22 PM
why my program can not run correctly?

m_lstA.remove(*iter); <-----error!!!!


///// part code as follow:


class A
{
public:
A();
virtual ~A();
bool operator== (const A& rhs){
return rhs.m_strName == m_strName && rhs.m_nNum == m_m_nNum;
};

CString m_strName; //
int m_nNum;
};

....

std::list<A> m_lstA;

......

std::list<A>::iterator iter = m_lstA.begin();
for(; iter != m_lstA.end(); ++iter){
if(iter->m_strName == strName){
m_lstA.remove(*iter); <----error!!!!!!!!
}
}

Gabriel Fleseriu
April 7th, 2003, 01:39 AM
Your code doesn't work because remove() will invalidate iter.

std::list<A>::iterator iter = m_lstA.begin(), r_i;
for(; iter != m_lstA.end(); ){
if(iter->m_strName == strName){
r_i = iter++;
m_lstA.remove(*r_i);
}
else{
++iter;
}
}