caps lock
caps lock

Reputation: 511

iterator go back to beginning in a recursive method

I'm having a lot of trouble with a method I wrote for a game. I'm moving "cubes" from right to left in a cartesian plane, and before moving a cube I need to check if it can moves. Cube can push another cube (and many other) until there's not a wall. I don't understand why my iterator (it) is reset to the beginning after I recall the method, I can see it with the 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;
}

EDIT : answer to myself

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

Upvotes: 0

Views: 702

Answers (1)

R Sahu
R Sahu

Reputation: 206697

I don't understand why my iterator (it) is reset to the beginning after I recall the method, I can see it with the debbuger

When you call the function recursively, the iterators in the next invocation of the have no relationship with the iterators in the previous invocation of function. When you use std::vector<Cube>::iterator it = vect.begin();, it makes sense that that it points to the start of the vector.

Upvotes: 1

Related Questions