【发布时间】:2014-03-13 20:38:31
【问题描述】:
我需要制作一个非常大的 3D 数组。大,我的意思是6000x1000x1000。每个元素都包含一个包含 3 个双精度的结构。该数组表示一个物理向量场,每个数组元素都包含向量值。
我需要动态声明数组,并且已经阅读了两种方法:使用向量类或使用指针。两个例子如下所示:
#include<iostream>
using namespace std;
struct myVector {
double Bx;
double By;
double Bz;
};
#define HEIGHT 10
#define WIDTH 10
#define DEPTH 50
//these are your sizes
void fill(myVector ***p3DArray);
void print(myVector ***const p3DArray);
int main() {
myVector ***p3DArray; //any name you want
// Allocate memory
// Replace "Struct" with the name of your struct
p3DArray = new myVector**[HEIGHT];
for (int i = 0; i < HEIGHT; ++i) {
p3DArray[i] = new myVector*[WIDTH];
for (int j = 0; j < WIDTH; ++j)
p3DArray[i][j] = new myVector[DEPTH];
}
// Assign values
p3DArray[0][0][0].Bx = 3.6;
p3DArray[1][2][4].Bz = 4.0;
fill(p3DArray);
//print(p3DArray);
// De-Allocate memory to prevent memory leak
for (int i = 0; i < HEIGHT; ++i) {
for (int j = 0; j < WIDTH; ++j)
delete [] p3DArray[i][j];
delete [] p3DArray[i];
}
delete [] p3DArray;
return 0;
}
和
#include <vector>
#include <iostream>
using namespace std;
struct myVector {
double Bx;
double By;
double Bz;
};
#define HEIGHT 1000
#define WIDTH 1000
#define DEPTH 500
void fill(vector<vector<vector<myVector>>> &Array);
void print(vector<vector<vector<myVector>>> &Array);
int main() {
vector<vector<vector<myVector> > > array3D;
// Set up sizes. (HEIGHT x WIDTH)
array3D.resize(HEIGHT);
for (int i = 0; i < HEIGHT; ++i) {
array3D[i].resize(WIDTH);
for (int j = 0; j < WIDTH; ++j)
array3D[i][j].resize(DEPTH);
}
// Put some values in
array3D[1][2][5].Bx = 6.0;
array3D[3][1][4].By = 5.5;
fill(array3D);
return 0;
}
对于 1000x1000x500 的尺寸,我的计算机内存不足并死机。我需要比这更大。使用 sizeof(),我发现单个元素占用 24 个字节。对于 1000x1000x500 元素,即 12 Gb。我正在使用 Microsoft Visual c++ 2010、64 位调试器和操作系统,并且有 8 Gb 的 RAM。
我只是没有足够的 RAM,还是有更好的方法来做到这一点?
谢谢
【问题讨论】:
-
你不能把你的问题分解成更小的元素吗?
-
首先,如果您要使用这样的老式数组,请将它们保存在 std::unique_ptr 中,这样您就不会忘记删除它们。您不想同时在内存中塞满这么多数据......典型的替代方法是流式传输(即一次处理一小部分数据),或者如果这不起作用,则将数据存储在数据库或只是在磁盘上的块中,可以根据需要将其提取到内存中。
-
哇……现在这是一个大数组……即使您可以改进它,也可能需要更多内存。
标签: c++ arrays memory-management dynamic 64-bit