本文介绍了如何声明一个可以在整个程序中使用的全局2d 3d 4d ...数组(堆版本)变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class1.cpp

class1.cpp

int a=10; int b=5; int c=2;
//for this array[a][b][c]

int*** array=new int**[a];


for(int i =0; i<a; i++)
{ 
    array[i] = new int*[b];        
    for(int k =0; k<b; k++) 
    {
       array[i][k] = new int[c];
    }  
}

我如何在其他.cpp文件中使用此数组?

how can i use this array in other .cpp files ?

推荐答案

代替手动分配数组,至少应使用std::vector.您要做的是拥有一个包含以下内容的头文件

Instead of manually allocating an array you should at least use a std::vector. What you would do is have a header file that contains

extern std::vector<std::vector<std::vector<int>>> data;

要包含在所有要与您共享矢量的cpp文件中,然后在单个cpp文件中包含

that you will include in all the cpp files you wish to share the vector with and then in a single cpp file have

std::vector<std::vector<std::vector<int>>> data = std::vector<std::vector<std::vector<int>(a, std::vector<std::vector<int>>(b, std::vector<int>(c)));

现在您将拥有一个共享的全局对象,并且该对象具有受管理的生存期.

and now you will have a global object that is shared and it has a managed lifetime.

不过,您实际上不应该使用嵌套向量.它可以分散内存中的数据,因此对缓存不是很友好.您应该使用具有单个维度向量的类,并使用数学假装它具有多个维度.一个非常基本的例子看起来像

You shouldn't really use a nested vector though. It can scatter the data in memory so it isn't very cache friendly. You should use a class with a single dimension vector and pretend that it has multiple dimensions using math. A very basic example of that would look like

class matrix
{
    std::vector<int> data;
    int row; // this really isn't needed as data.size() will give you rows
    int col;
    int depth;
public:
    matrix(int x, int y, int z) : data(x * y * z), row(x), col(y), depth(z) {}
    int& operator()(int x, int y, int z) { return data[x + (y * col) + (z * col * depth)]; }
};

然后头文件将是

extern matrix data;

一个cpp文件将包含

matrix data(a, b, c);

这篇关于如何声明一个可以在整个程序中使用的全局2d 3d 4d ...数组(堆版本)变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:52