Hello everyone, my professor just gave me assignment to make any boardgame we want using the console. He wants us to use OOP and make user of the STL also. I chose battleship and have set about making my class design but have run into a problem right at the beginning. I am trying to populate the gameboard which is a vector<vector<char>> with all 'O' as you can see using my size member (Like board[SIZE][SIZE]). But the code below is giving me a runtime error and I am not sure why. It seems logical to me.
1 2 3 4 5 6
void GameBoard::populateBoard()
{
for (unsigned i = 0; i != SIZE; ++i)
for (unsigned j = 0; j != SIZE; ++j)
board[i].push_back('O');
}
Anwyays was wondering if anyone could point out why it is doing this. I was also wondering something else. At first I wanted to make it so the GameBoard class's constructors took care of populating the vector but I didn't really know how. Thanks in advance for the help, and also I am not looking for complete answers to my problem but if you could atleast give me a hint that would be great.
Just a update I figured out how to get the function working but was still wondering if there would be a way to initialize the vector of vectors within the constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13
void GameBoard::populateBoard()
{
for (unsigned i = 0; i != SIZE; ++i)
{
vector<char> temp;
for (unsigned j = 0; j != SIZE; ++j)
{
temp.push_back('O');
}
board.push_back(temp);
}
}
From what I gather from this sites reference section (link above), you can call the second constructor (read: second constructor listed on the provided link) to fill the vector with a specified number of a specified element. So something like: