所以基本上我制作了一个二维数组,Component pixel[][]
,其中 Component
是类,我正在尝试更改其中一个变量网格(由尺寸值制成)。出于某种原因,当我运行代码时,大部分代码都会打印出 0
和 1
,其中一个除外。
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;
只需替换int
与 Component
关于c++ - 使用类的属性制作二维数组,更改值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026954/