如何将一个巨大的二维数组初始化为类中的空间
How can I initialize a huge 2D array to spaces within a class?
首先让我告诉你,我学习过C和C++,但我对OOP的了解非常有限。我基本上希望,一旦我创建了一个对象到类输出,我的整个数组outpt就被初始化为空格(字符号32)。MAXROWS和MAXCOLS被定义为const int,目前为25和80,但我可能会更改它们。
class output{
private:
int score;
char outpt[MAXROWS][MAXCOLS];
void rand_platform()
{
int platform_start = rand() % (MAXCOLS-20);
int platform_length = rand() % 10 + 10;
for (int i=0; i<platform_length; i++) {
outpt[MAXROWS-1][platform_start+i]=219;
}
}
void bring_screen_down()
{ //this part brings whole screen 1 row up
score++;
for (int i=1;i<MAXROWS;i++) {
for (int j=0;j<MAXCOLS;j++) {
outpt[i-1][j] = outpt[i][j];
}
}
for (int j=0;j<MAXCOLS;j++) {
outpt[MAXROWS-1][j] = 0;
}
if (!(score%10))
rand_platform();
}
public:
void print()
{
system("CLS");
for (int i=0; i<MAXCOLS/2-2;i++)
cout << ' ';
printf("%04dn",score);
for (int i=0;i<MAXROWS;i++) {
for (int j=0;j<MAXCOLS;j++) {
cout << outpt[i][j];
}
cout << endl;
}
bring_screen_down();
Sleep(200); // alternately for(int i=0; i<3500000;i++);
}
void output()
{
score=0;
fill_n(outpt, num_space_req, ' ');
}
};
class output {
//...
output() {
memset( &outpt[0][0], ' ', sizeof(char) * MAXROWS * MAXCOLS );
}
}
这将从输出[0][0]的地址开始,将(MAXROWS*MAXCOLS)个字符设置为"(32)的值。由于您将每个元素设置为相同的值,因此这是一种快速的方法
首先,您可以在构造函数中清除数组。
要初始化一个类,必须使用一个所谓的构造函数。例如像这个
#include <cassert>
#include <algorithm>
const std::ptrdiff_t max_rows;
const std::ptrdiff_t max_cols;
class output {
private:
char data_[max_rows][max_cols];
public:
output()
{
assert(max_rows > 0 && max_cols > 0);
std::fill_n(&data_[0][0], max_rows*max_cols, ' ');
}
void print() { /* your output */ }
};
对于这种维度大小处理,最好使用boost::multi_array
容器或std::array
容器。这些C样式的数组非常容易出错。即使这样也可以更安全
class output {
private:
std::array<char,max_rows*max_cols> data_;
public:
output()
{
for (char& x : data_) // can not be out of bounds
x = ' ';
// std::fill(data_.begin(), data_.end(), ' ');
}
void print() { /* your output */ }
};
相关文章:
- 在C++中初始化第一维大小未知的二维数组
- 使用lambdas初始化多维数组
- 如何在编译时初始化静态二维数组
- 如何在 c++ 中初始化构造函数中的二维数组
- 二维数组未正确初始化
- 从二维数组中的char*初始化c++字符串时,读取大小为1的无效值
- 二维数组初始化
- 使用 char 初始化多维数组
- 初始化和删除二维数组
- 初始化多维数组中的所有位置
- 初始化多维数组的元素
- 二维数组的初始化数组
- 二维数组初始化值
- 初始化具有特定值的可变二维数组
- 如何在c++中初始化多维数组
- 动态初始化多维数组时出现重复变量错误
- 如何用null声明和初始化多维数组
- 用零初始化多维数组
- 如何在c++构造函数中初始化多维数组
- 如何在Qt/ c++中有效地重新初始化多维数组