I'm just confused on where to start like how this actually draws a board using a 2d vector. I haven't edited any code and the code below is what is needed. It's unfinished code with several other functions I had to delete so I can just focus on creating the board first. How would I approach with creating this board with just a 3x3 of dashes?
How would I actually print out the 3x3 so it looks like this:
- - -
- - -
- - -
I'm thinking of something like:
// 2D display of board contents
void displayBoard(vector<vector<char>>& board) {
// Your code here
for (int i = 0; i < nRows; i ) {
}
}
But am not too sure how to continue it and print it out.
// Tic-tac-toe board - user plays against computer; displays board after each move
#include <iostream>
#include <vector>
using namespace std;
const int nRows = 3;
const int nCols = 3;
// 2D display of board contents
void displayBoard(vector<vector<char>>& board) {
// Your code here
}
// Game loop
int main() {
vector<vector<char>> board{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
displayBoard(board);
}
CodePudding user response:
Each vector
knows its own size()
, so your display function can look something like this:
// 2D display of board contents
void displayBoard(const vector<vector<char>>& board) {
for (size_t i = 0; i < board.size(); i ) {
for (size_t j = 0; j < board[i].size(); j ) {
cout << board[i][j] << ' ';
}
cout << endl;
}
}
Or simpler:
// 2D display of board contents
void displayBoard(vector<vector<char>>& board) {
for (const auto &vec : board) {
for (auto ch : vec) {
cout << ch << ' ';
}
cout << endl;
}
}
CodePudding user response:
For your question, what does
vector<vector<char>> board{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
do? It initializes the board
, a vector
of vector
s, using list initialization. Each {'-', '-', '-'}
is a single vector. Three of these vector
s in the list provides the "vector
of vector
s" dimensionality.
{'-', '-', '-'}
position 0 1 2 for each inner vector
{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
|_____________| |_____________| |_____________|
^ ^ ^
position 0 1 2 for the outer vector
So, when accessing elements, the first index chooses the vector, the second index chooses the element within that vector:
{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
^ ^ ^
| | |
board[0][0] | |
board[1][1] |
board[2][2]
The other answer shows you how to print.