簡體   English   中英

迭代器從遞歸方法開始

[英]iterator go back to beginning in a recursive method

我為游戲編寫的方法遇到很多麻煩。 我正在笛卡爾平面中從右向左移動“立方體”,在移動立方體之前,我需要檢查它是否可以移動。 多維數據集可以推另一個多維數據集(以及許多其他多維數據集),直到沒有牆為止。 我不明白為什么我在調用該方法后將迭代器(it)重置為開始,我可以使用debbuger看到它

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)重置為開始,我可以使用debbuger看到它

當您遞歸調用該函數時,下一次調用的迭代器與上一次調用函數的迭代器沒有關系。 當您使用std::vector<Cube>::iterator it = vect.begin(); ,這是有道理的,是it指向的開始vector

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM