Search code examples
c++vectorallegro

Vector iterator error


I am writing an Allegro based snake game and have a problem with vector which contains the coordinates of the parts of the snake.

Here is the function which deletes the last element of the snake and adds a new one. Previously I have declared vector <int> snake_x ; vector <int> snake_y; and I have also pushed back required numbers in the vector.

 void moove_snake(int direction){
switch (direction){
    case UP:
    {
        vector <int>::iterator xIter;
        vector <int>::iterator yIter;
        snake_x.erase(snake_x.begin());
        snake_y.erase(snake_y.begin());
        xIter=snake_x.end();
        yIter=snake_y.end();
        snake_x.push_back(*xIter);
        snake_y.push_back(*yIter-20);
        draw();
        al_flip_display();
        al_rest(0.4);
        break;
    }
    case DOWN:
    {
        vector <int>::iterator xIter;
        vector <int>::iterator yIter;
        snake_x.erase(snake_x.begin());
        snake_y.erase(snake_y.begin());
        xIter=snake_x.end();
        yIter=snake_y.end();
        snake_x.push_back(*xIter);
        snake_y.push_back(*yIter+20);
        draw();
        al_flip_display();
        al_rest(0.4);
        break;
    }
    case LEFT:
    {
        vector <int>::iterator xIter;
        vector <int>::iterator yIter;
        snake_x.erase(snake_x.begin());
        snake_y.erase(snake_y.begin());
        xIter=snake_x.end();
        yIter=snake_y.end();
        snake_x.push_back(*xIter-20);
        snake_y.push_back(*yIter);
        draw();
        al_flip_display();
        al_rest(0.4);
        break;      
    }
    case RIGHT:
    {
        vector <int>::iterator xIter;
        vector <int>::iterator yIter;
        snake_x.erase(snake_x.begin());
        snake_y.erase(snake_y.begin());
        xIter=snake_x.end();
        yIter=snake_y.end();
        snake_x.push_back(*xIter+20);
        snake_y.push_back(*yIter);
        draw();
        al_flip_display();
        al_rest(0.4);
        break;
    }
}

}

When I run the exe file it opens a error message box saying that vector iterator not dereferencable . What it means ?


Solution

  •     xIter=snake_x.end();
        yIter=snake_y.end();
    

    you cann't do this *xIter or *yIter.

    Returns an iterator referring to the past-the-end element in the vector container.

    The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

    Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container.

    If the container is empty, this function returns the same as vector::begin.