Help with a Console Battleship Game

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);
    }
}
http://www.cplusplus.com/reference/vector/vector/vector/

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <vector>
#include <iostream>

int main()
{
    const int SIZE = 10;
    std::vector<std::vector<char> > vec;
    for (auto i = 0; i != SIZE; i++)
    {
        vec.push_back(std::vector<char>(100, 'O'));
    }
    
    for (auto i = 0; i != SIZE; i++)
    {
        for (auto j = 0; j != SIZE; j++)
        {
            std::cout<< "vec["<< i<< "]["<< j<< "]: "<< vec[i][j]<< std::endl;
        }
    }
    
    return 0;
}
vec[0][0]: O
vec[0][1]: O
vec[0][2]: O
[..]
vec[9][7]: O
vec[9][8]: O
vec[9][9]: O


Is that something like what you mean?
Topic archived. No new replies allowed.