Debug代码时,碰到一个关于迭代器的崩溃错误(仅限Debug模式,release会被容错)。查阅相关资料和参考别人的博客,做了一些总结。
该问题主要原因就是在使用容器类中的迭代器时没有加以判断有效性,访问了非法的iterator。
一个简单示例:
for(unsigned int idx2=0; idx2<size; idx2++)
{
map<unsigned int, unsigned int>::iterator it = tmp_map.find(idx2);
unsigned int idx = it->second; //<--- Causing the error !!
...
//do something with idx
}
修改后:
for(unsigned int idx2=0; idx2<size; idx2++)
{
map<unsigned int, unsigned int>::iterator it = tmp_map.find(idx2);
if(it != tmp_map.end())
{
unsigned int idx = it->second;
...
//do something with idx
}
}
总结
对于容器的迭代器(iterator)操作,一定要小心迭代器非法的情况,此时对于迭代器的任何操作,都会导致显性或者隐性的问题,尤其很多容器在erase操作后,迭代器会失效或者指向新的位置,此时需要根据自己实际情况加以判断或修改,保证之后对于它的操作合法。
参考:
https://blog.csdn.net/beyongwang/article/details/53074704
https://stackoverflow.com/questions/13496644/c-map-set-iterator-not-dereferencable