如何在C++类中初始化可变大小的2D数组

How do I initialize a 2D array of variable size in a C++ class?

本文关键字:数组 2D 初始化 C++      更新时间:2023-10-16

我正在开发一个井字游戏程序,我需要在一个类中创建一个可变大小的2D数组。我现在是这样写的:

class ticTacToe
{
     public:
         ticTacToe();
         void display();
         bool moveIsValid();
     private:
         int rows;
         int cols;
         int board[rows][col];
}

我从构造函数中的文件中读取了板,但我不知道如何使其具有可变大小,以便我可以读取任何大小的板,然后在类外访问它。

"我从构造函数中的文件中读取了板,但我不确定如何使其具有可变大小,以便我可以读取任何大小的板"

在c++中,您使用std::vector,而不是像一样的原始数组

class ticTacToe {
     public:
         ticTacToe();
         void display();
         bool moveIsValid();
     private:
         int rows;
         int cols;
         std::vector<std::vector<int>> board; // <<<<
};

动态分配可以在构造函数中应用如下:

ticTacToe(int rows_, int cols_) : rows(rows_), cols(cols_) {
    board.resize(rows,std::vector<int>(cols));
}

,然后在类外访问它

好吧,我不确定这是否真的是个好主意,但你可以简单地为成员变量添加一个访问器函数

 std::vector<std::vector<int>>& accBoard() { return board; }

更好的设计方法是IMHO,提供类似于从std::istream:读取的单独功能

 void ticTacToe::readFromStream(std::istream& is) {
     // supposed the first two numbers in the file contain rows and cols
     is >> rows >> cols;
     board.resize(rows,std::vector<int>(cols));
     for(int r = 0; r < rows; ++r) {
         for(int c = 0; c < cols; ++c) {
             cin >> board[r][c];
         }
     }
 }

对于真正的代码,你当然会检查输入错误,比如

 if(!(is >> rows >> cols)) {
    // handle errors from input
 }

如果这是家庭作业,并且您不能使用标准库:

// Declaration
int rows;
int columns;
int **board;
// Construction
board = new int*[rows];
for (int i = 0; i < rows; i++) {
    board[i] = new int[columns];
}
// Destruction

for (int i = 0; i < rows; i++) {
    delete[] board[i];
}
delete[] board;

更新:您可以执行单个分配,但这样做会更容易。

您要么需要一个动态大小的数组

int* board;

那么你的构造函数就是

ticTacToe::ticTacToe(int _rows, int _cols)
: rows{_rows}, cols{_cols}
{
    board = new int[rows * cols];
}

还有你的自毁

ticTacToe::~ticTacToe()
{
    delete[] board;
}

或者最好使用std::vector

std::vector<int> board;

那么你的构造函数就是

ticTacToe::ticTacToe(int _rows, int _cols)
: rows{_rows}, cols{_cols}
{
    board.resize(_rows * _cols);
}

我建议您使用指针对指针。

#include <iostream>
#include <cstdlib>
using namespace std;
class ticTacToe{
private:
    int rows;
    int cols;
    int **board; // POINTER TO POINTER
public:
    ticTacToe(int a,int b){
        rows=a;
        cols=b;
        board=new int*[rows];
        for (int k = 0; k < rows; ++k) {
            board[k]=new int[cols];
        }
        /*LET'S INITIALIZE CELL VALUES TO= 0*/
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                board[i][j]=0;
            }
        }
    }
    void display();
    bool moveIsValid();
};