KJG
KJG

Reputation: 31

Vector at() out of range error after initializing

Hello all (first post to SO here). I am working on a text based C++ game (Ants vs Some Bees) as a side project where I have a vector of Insect pointers that I initialize in an init function

void Colony::initBoard()
{
    vector<Insect*> gameBoard (10, nullptr);

    //check to see that vector is properly intialized
    for (auto &it : gameBoard)
    {
        std::cout << it << std:: endl;
    };
    //check the size
    cout << gameBoard.size() << endl;
}

The next goal is to place some of the Ants at a specified point in the vector, and my ant class inherits from the insect class. This is where I am getting a vector out of range error when using the .at() method, and the vector shows a size of zero.

void Colony::createAnt()
{   
    int position = 0;
    cout << "Where do you want to set your Ant? " << endl;
    cin >> position;
    //checking for size (0 here for some reason)
    cout << gameBoard.size() << endl;

    ...//validation stuff done here, not relevant to post

    gameBoard.at(position) = new Ant(position);
    isOccupied = true;
}

When running this code in main, I get a size of 10 when the init function is called, and a size of 0 when the place ant is called, and I am not sure why.

My main function so far which is just testing the functionality of this function.

    Colony col;
    col.initBoard();
    col.createAnt();

vector<Insect*> gameBoard; is the private member variable in the Colony class. My thoughts is that the vector is somehow going out of scope, but I am not sure how to fix. Thanks in advance for any tips/suggestions

Upvotes: 1

Views: 180

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596101

In initBoard(), you have declared a local variable named gameBoard that you are filling instead of the class member of the same name.

Change this line:

vector<Insect*> gameBoard (10, nullptr);

To this instead:

gameBoard.resize (10, nullptr);

That being said, since you know the number of elements at compile time, consider using a fixed array instead of a std::vector, eg:

std::array<Insect*, 10> gameBoard;

Either way, you should be storing std::unique_ptr<Insect> elements instead of raw Insect* pointers, eg:

gameBoard.at(position).reset(new Ant(position));

Or:

gameBoard.at(position) = std::make_unique<Ant>(position);

Upvotes: 1

Related Questions