如何在C++类中初始化可变大小的2D数组
How do I initialize a 2D array of variable size in a C++ class?
我正在开发一个井字游戏程序,我需要在一个类中创建一个可变大小的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();
};
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何打印 2D 字符数组C++
- 如何将数组 2d 作为参数从函数传递并返回数组 2d 此函数
- 数组 2D 多个值
- 创建数组数组 (2D),而无需在 Java 中初始化内部数组
- 如何在C++中将文本文件传输到数组2D
- 从同一类的另一个方法调用数组2D-C++
- 获取地址在数组2d中的位置