0

尝试迭代另一个对象指向的地图时出现此错误。当我不使用指针时它可以工作。(迭代成员地图“碎片”)因此我想知道该怎么做,或者是否不可能像这样迭代地图?:

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;
}

提前致谢!

4

2 回答 2

1

The removePiece() function removes the element that it is referring to, invalidating it. An attempt is then made to increment it resulting in the assertion failure. From 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():

newBoard->pieces.clear();
于 2012-07-09T13:14:41.610 回答
0

要解决此问题,请去掉++itfor 循环中的 并替换it->firstit++->first.

(这将增加迭代器并使用副本调用 erase()。)

于 2012-07-09T13:19:49.650 回答