【问题标题】:iterator go back to beginning in a recursive method迭代器以递归方法回到开头
【发布时间】:2015-04-22 20:44:21
【问题描述】:

我为游戏编写的方法遇到了很多麻烦。我在笛卡尔平面上从右向左移动“立方体”,在移动立方体之前,我需要检查它是否可以移动。立方体可以推动另一个立方体(和许多其他立方体),直到没有墙。 我不明白为什么我的迭代器(它)在我回忆方法后重置到开头,我可以用调试器看到它​​

bool Cube::moveLeft(std::vector<Cube>& vect, int column, int line){
    //freeSpace == false  (if we have a cube at the left position)
    bool freeSpace = Cube::whatIsClose(vect, column, line - 1);
    //isWall == true (if we have a wall at the left position)
    bool isWall = Cube::whatIsClose(vect, column, line - 1, WALL);

    for (std::vector<Cube>::iterator it = vect.begin(); it < vect.end(); ++it){
        //if space is avaible
        if (freeSpace){
            //we iterate 
            if ((it->getX() == column) &&
                (it->getY() == line)){
                //we can move to the left
                it->setY(line - 1);
                return true;
            }
        }
        //else if there s a cube at the left position
        else if (!freeSpace){
            //if its a wall we cant move
            if (isWall){
                return false;
            }
            else//the cube is not a wall
            {       
                //we check if this cube can move and this call will move it
                if (Cube::moveLeft(vect, column, line - 1)){        
                    //here is the problem :
                    //my iterator it is reinitialize to 0..
                    it->setY(line - 1);
                    return true;
                }
            }
        }
    }
    return false;
}

编辑:回答我自己

            if (freeSpace){
                setY(line - 1);
                return true;
            }

【问题讨论】:

  • 附注:使用!=:it != vect.end()

标签: c++ recursion iterator reset


【解决方案1】:

我不明白为什么我的迭代器(它)在我回忆方法后重置到开头,我可以用调试器看到它​​

递归调用函数时,下一次调用的迭代器与上一次调用函数的迭代器没有关系。当您使用std::vector&lt;Cube&gt;::iterator it = vect.begin(); 时,it 指向vector 的开头是有道理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-21
    • 2016-11-10
    • 2013-06-14
    • 2021-12-24
    相关资源
    最近更新 更多