STL容器迭代器存在失效的狀況,須要瞭解STL容器的實現方式,才能理解那種迭代器在何種狀況下會失效。spa
std::vector<std::int> iter = m_vResult.begin(); for(; iter !=m_vResult.end(); iter++){ if(*iter == 0){ m_vResult.erase(iter); //iter被刪除後就失效了。iter++動做是未定義 } }
正確寫法以下指針
std::vector<std::int> iter = m_vResult.begin(); while(iter !=m_vResult.end()){ if(*iter == 0){ m_vResult.erase(iter++); } else{ iter++; } }
或者code
std::vector<std::int> iter = m_vResult.begin(); while(iter !=m_vResult.end()){ if(*iter == 0){ iter = m_vResult.erase(iter); } else{ iter++; } }