将代码转换为数组和显示

时间:2010-07-30 06:13:02

标签: c++ arrays function

如何将其转换为数组?我需要一块板来显示空格,当用户输入它时,用另一个函数填充X或O.当前的电路板工作我想把它变成一个数组[3] [3]并显示数组的内容。

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;
 }
}

2 个答案:

答案 0 :(得分:1)

您可以让showboard()函数接受对chars的3x3数组的引用。奇怪的参数char (&squares)[3][3]表示“引用名为chars的{​​{1}}的3x3数组。”

squares

或者,这是一个使用for循环的实现:

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);
}

答案 1 :(得分:0)

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;
    }
}