我试图在c ++中创建一个巨大的2D数组,如下所示:
float array[1000000][3];
我必须在这个包含3个组件的数组中存储一些值。这将通过两个1000循环的循环迭代完成。当我尝试运行它时,我收到一个错误:
Segmentation fault
这是我的一些代码:
int m=0,c=0;
float error;int count=0;
array<array<float, 1000000>, 3> errors;
for(int i=0; i<1000; i++){
for(int j=0; j<1000; j++){
error=distance(j+20,m,c,1000-matrix(1,j));
errors[count][0]=error;
errors[count][1]=m;
errors[count][2]=c;
c++;
count++;
}
m++;
c=0;
}
sort(errors.begin(), errors.end());
cout<<errors[0][0]<<endl<<errors[0][1]<<endl<<errors[0][2]<<endl;
即使在评论排序后错误也会继续...
matrix(1,j)是一个矩阵,我正在使用这个方法访问它的元素。
我想要最小的错误值和m和c的值的集合,其中错误是最小的。
有什么办法可以实现吗?提前致谢。
您可以使用array
轻松执行任务。在这里你可以:
#include<array>
using namespace std;
然后,让我们创建您的数据数组:
const int N = 1000000;
const int M = 3;
array<array<float, N>, M> my_array;
您可以执行以下操作来填充此新创建的数组:
for(int i=0; i < N; i++){
for(int j=0; j < M; j++){
my_array[i][j] = 0.0f; // Just for example
}
}
有关如何使用array
库的更多信息,请参阅here
如果您不想使用array
,您还可以按以下步骤操作:
const int N = 10000000;
const int M = 3;
float *my_array
my_array = new float[N*M]; // give it a memory on the stack
if(my_array == nullptr){
cerr << "ERROR: Out of memory" << endl;
}
for(int i=0; i < N; i++){
for(int j=0; j < M; j++){
*(my_array + i*N + j) = 0.0f; // Just for example
}
}
确保通过执行以下操作释放您获得的内存:
delete [] my_array;