所以基本上我做了一个2-D数组,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;
}
答案 0 :(得分:0)
从https://stackoverflow.com/a/31090156/3349368看,请尝试使用STL 30/10/2015
。
从上面的链接
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
答案 1 :(得分:0)
当我学到很难的方法时,必须在编译时知道数组大小。您不允许cin&gt;&gt;数组大小并在运行时设置它们。它们必须是const int,在代码中明确声明。如上所述,如果您希望能够在运行时更改其大小,请使用std :: vector,因为它们是动态的,而不是静态的。