我需要制作一个非常大的3D数组。大,我的意思是6000x1000x1000。每个元素都包含一个包含3个双精度的结构。该数组用于表示物理向量字段,每个数组元素用于包含向量值。
我需要动态声明数组并读取两种方法:使用vector类或使用指针。两个例子如下所示:
#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。我使用的是64位调试器和操作系统Microsoft Visual c + + 2010,并且拥有8 Gb的RAM。
我没有足够的内存,或者有更好的方法吗?
由于
答案 0 :(得分:0)
要达到6000x1000x1000的目标,您将无法立即将所有数据存储在RAM中。对于那么多元素,每个元素24字节,你说的是大约134 GB的数据。
您可能想要做的是设计自己的类,从磁盘中检索元素,而不是在一个连续的内存块中分配所有内容。
答案 1 :(得分:0)
编写一个类(让我们调用它&#34; 3dArray&#34;),它隐藏了客户端的存储实现。在该课程中,您不应存储3D数组的全部内容。仅存储 值,这些值是明确写入的。在您的示例中,您只设置了两个数据点,那么为什么不仅存储这两个数据点(以任何方式)?为了做到这一点,远离需要带有HEIGHT x WIDTH x DEPTH元素的向量或数组的想法。相反,使用类似的东西:
std::map<Coord, myVector> written_points;
...
void 3dArray::SetPoint(int x, int y, int z, myVector const &value)
{
written_points[Coord(x, y, z)] = value;
}
此外,在返回操作结果时,返回推迟实际计算的代理对象。
例如,让我们说你的班级应该支持乘法:
3dArray a1;
3dArray a2;
3dArray a3 = multiply(a1, a2);
std::cout << a3.GetPoint(10, 20, 30);
这里几乎完全抛弃了乘法的结果 - 只需要整个巨大结果的一个数据点。为什么要增加整个事物?如果这个想法看起来很有趣,请看看Scott Meyers的第17项&#39; 更有效的C ++ 书:&#34;考虑使用延迟评估&#34;。
最后,请记住,任何此类优化技术的有效性取决于数据在应用程序中的使用方式。