1、报错
“map/set iterator not incrementable”,程序运行至一般报错
for (ActionBindings::const_iterator cit = _bindings.begin();
cit != _bindings.end(); cit++)
{
if (actionType == (*cit).second._type)
{
cit = _bindings.erase(cit);
}
} 在cit++这行报错。
2、内码解析
当执行完erase之后,cit已经指向空,无法进行++操作。
在C++11中,std::map/vector的erase方法返回iterator,能够指向被删除的下一个。(The other versions return an iterator to the element that follows the last element removed (or map::end, if the last element was removed).)
3、解决方案
执行完erase,保存cit用于指向下个对象
ActionBindings::const_iterator cit = _bindings.begin();
while (cit != _bindings.end())
{
if (actionType == (*cit).second._type)
{
cit = _bindings.erase(cit);
}
else
{
cit++;
}
}
本文介绍了一种常见的C++编程错误——在使用map或set迭代器进行元素删除时遇到的“迭代器不可递增”错误。文章分析了错误产生的原因,并提供了一个有效的解决方案,避免迭代器失效的问题。
641

被折叠的 条评论
为什么被折叠?



