简体   繁体   English

C ++,将迭代器用于指向的地图容器时出错。 映射/设置迭代器不可递增

[英]C++, error when using iterator for a map container that is pointed to. map/set iterator not incrementable

I am getting this error when trying to iterate over a map that is pointed to by another object. 尝试迭代另一个对象指向的地图时出现此错误。 It works when I am not using a pointer. 当我不使用指针时,它可以工作。 (Iterating over the member map "pieces") I am therefore wondering what to do, or if it's not possible to iterate through the map like this ? (遍历成员映射“件”)因此我想知道该怎么做,或者是否不可能像这样遍历整个映射? :

Board * Board::ccBoard(){

Board * newBoard = new Board();
map<Vec2, Piece>::iterator it;
for (it = newBoard->pieces.begin(); it != newBoard->pieces.end(); ++it)
    newBoard->removePiece(it->first);
return newBoard;
}

Thanks in advance! 提前致谢!

The removePiece() function removes the element that it is referring to, invalidating it . 所述removePiece()函数删除该元素it指的是,无效it An attempt is then made to increment it resulting in the assertion failure. 然后尝试增加it导致断言失败。 From map::erase() : map::erase()

References and iterators to the erased elements are invalidated. 对已删除元素的引用和迭代器无效。

I am unsure what the intention of the for loop is, it appears that it would effectively empty the map in which case just use map::clear() : 我不确定for循环的意图是什么,看来它将有效地清空map在这种情况下,只需使用map::clear()

newBoard->pieces.clear();

To fix, get rid of the ++it in the for loop and replace it->first by it++->first . 要修复,摆脱++it的for循环和取代it->firstit++->first

(This will increment the iterator and call erase() using a copy.) (这将使迭代器增加,并使用副本调用Ease()。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM