c++ - 使用类的属性制作二维数组,更改值时遇到问题

标签 c++ arrays class 2d

所以基本上我制作了一个二维数组,Component pixel[][],其中 Component 是类,我正在尝试更改其中一个变量网格(由尺寸值制成)。出于某种原因,当我运行代码时,大部分代码都会打印出 01,其中一个除外。

class Component {
public:
    int label;
    int order;
};

int main() {
    int dimension;
    float density;
    float R;

    do
    {
        cout << "Please enter a grid size between 5 and 15: ";
        cin >> dimension;
        if(dimension > 15 || dimension < 5)
        {
            cout << "Needs to be between 5 and 15" << endl;
        }
    }while(dimension > 15 || dimension < 5);

    do
    {
        cout << "Enter a density value between 0.0 and 1.0: ";
        cin >> density;
        if(density > 1.0 || density < 0.0)
        {
            cout << "Needs to be between 0.0 and 1.0" << endl;
        }
    }while(density > 1.0 || density < 0.0);

    Component pixel[dimension][dimension];

    srand (unsigned(time(NULL)));
    for (int row = 1; row <= dimension; row++)
    {
        for (int col = 1; col <= dimension; col++)
        {
            R = (float)rand()/(RAND_MAX+1);
            cout << R << " ";
            if (R < density)
            {
                pixel[row][col].label = 1;
            }
            else
                pixel[row][col].label = 0;
        }
        cout << endl;
    }
    cout << endl << endl;

    for (int row = 1; row <= dimension; row++)
    {
        for (int col = 1; col <= dimension; col++)
        {
            cout << pixel[row][col].label << " ";
        }
        cout << endl;
    }
    return 0;   
}

最佳答案

https://stackoverflow.com/a/31090156/3349368 可以看出,尝试使用 STL std::vector<std::vector<Component> >反而。

从上面的链接,

int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;

std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));

// Read from matrix.
int value = matrix[1][2];

// Save to matrix.
matrix[3][1] = 5;

只需替换intComponent

关于c++ - 使用类的属性制作二维数组,更改值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026954/

相关文章:

java - 如何获取初始化数组大小的用户输入(数组是全局声明的)JAVA

javascript - 使用 Nashorn 遍历数组

java - 静态错误: This class does not have a static void main method accepting String[].

c++ - 在 iOS 上使用 C++ 代码,创建静态库或与 Objective C 混合使用?

c++ - 编译多个文件时出现奇怪的 undefined reference 错误

c++ - 没有模板也能完美转发吗

PHP/SQL - 查询数组加载时间

c++ - 如何使用以集合作为参数的模板化客户端 display() 函数

php - 在 PHP 中使用 OOP 时在方法中使用函数

c++ - 重载 I/O 运算符 C++