如何将一个巨大的二维数组初始化为类中的空间

How can I initialize a huge 2D array to spaces within a class?

本文关键字:初始化 二维数组 空间 巨大 一个      更新时间:2023-10-16

首先让我告诉你,我学习过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 */ }
};