Search code examples
c++vectortic-tac-toe

Can anyone explain what "std::vector<std::vector<char>> board(3, std::vector<char>(3, ' '));" means


I came across this code for building a Tic-Tac-Toe game, and have no idea what it means. Can anyone explain in simple terms?

std::vector<std::vector<char>> board(3, std::vector<char>(3, ' '));

context:

void drawBoard(const std::vector<std::vector<char>> &board)
{
    for (const auto &row : board)
    {
        for (char cell : row)
        {
            std::cout << cell << " ";
        }
        std::cout << std::endl;
    }
}

int main()
{
    std::vector<std::vector<char>> board(3, std::vector<char>(3, ' '));
    char currentPlayer = 'X';
    int row, col;
    bool gameOver = false;

Solution

  • The line is using one of std::vectors constructors, twice:

    constexpr vector( size_type count,
                      const T& value,
                      const Allocator& alloc = Allocator() );
    

    This constructor is used to initialize the vector with count number of copies of value.

    So this ...

    std::vector<char>(3, ' ')
    

    ... constructs a vector of char with three elements, all being initialized to ' ' (space).

    In this ...

    std::vector<std::vector<char>> board(3, std::vector<char>(3, ' '));
    //                                   ^                    ^   ^
    //                                   |                    |   |
    //                                   |               ^    +-1-+
    //                                   |               |
    //                                   +-------2-------+
    

    ... the value_type is std::vector<char> and it makes three copies (2 in the graph above) of std::vector<char>(3, ' ') (1 in the graph above) which makes a 3x3 game board of char all initialized to ' '.