How can I turn this into an array? I need a board to show blank spaces and when the user enters it gets filled with a X or an O by another function. The current board works I would like to make it into a array[3][3] and display the contents of开发者_高级运维 the array.
void showboard(char &squareOne, char &squareTwo, char &squareThree, char &squareFour, char &squareFive, char &squareSix, char &squareSeven,
char &squareEight, char &squareNine)
{
cout << squareOne << "|" << squareTwo << "|" << squareThree << endl
<< "-+-+-"<< endl
<< squareFour << "|" << squareFive << "|" << squareSix << endl
<< "-+-+-"<< endl
<< squareSeven << "|" << squareEight << "|" << squareNine << endl;
}
}
You can have the showboard()
function accept a reference to a 3x3 array of chars
. The odd-looking parameter char (&squares)[3][3]
means "reference to a 3x3 array of chars
named squares
".
void showboard(char (&squares)[3][3])
{
std::cout << squares[0][0] << "|" << squares[0][1] << "|"
<< squares[0][2] << "\n" << "-+-+-"<< "\n"
<< squares[1][0] << "|" << squares[1][1] << "|"
<< squares[1][2] << "\n" << "-+-+-"<< "\n"
<< squares[2][0] << "|" << squares[2][1] << "|"
<< squares[2][2] << std::endl;
}
int main()
{
char s[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} };
showboard(s);
}
Alternatively, here's an implementation that uses a for loop instead:
void showboard(char (&squares)[3][3])
{
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
std::cout << squares[i][j];
if(j < 2) std::cout << "|";
}
std::cout << "\n";
if(i < 2) std::cout << "-+-+-" << std::endl;;
}
}
template <typename T, int nRows, int nCols>
class Matrix: public vector<vector<T>>
{
public:
Matrix()
{
for (int r = 0; r < nRows; ++r)
{
vector<T> row;
row.resize(nCols);
fill(row.begin(), row.end(), 0);
this->push_back(row);
}
}
int rows() const { return nRows; }
int columns() const { return nCols; }
};
typedef Matrix<int, 3, 3> Board;
void show(const Board& board)
{
for (int i = 0; i < board.rows(); ++i)
{
for (int j = 0; j < board.columns(); ++j)
cout << board[i][j] << " ";
cout << endl;
}
}
精彩评论