如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?

How to declare a global 2d 3d 4d ... array (heap version) variable that could be used in the entire program?

本文关键字:2d 3d 全局 4d 数组 版本 变量 程序 声明 何声明 一个      更新时间:2023-10-16

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文件中使用此数组?

与其手动分配数组,不如至少使用std::vector。 你要做的是有一个包含

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

您将包含在您希望与之共享矢量的所有 CPP 文件中,然后在单个 CPP 文件中具有

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)));

现在,您将拥有一个共享的全局对象,并且它具有托管的生存期。


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

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);

更喜欢std::arraystd::vector而不是原始数组。你有恒定的尺寸,所以使用std::array. 在头文件中声明它:

// header.h
#pragma once  // or use multiple inclusion guards with preprocessor
#include <array>
const int a = 10;
const int b = 5;
const int c = 2;
using Array3D = std::array<std::array<std::array<int,c>,b>,a>;
extern Array3D array3d;  // extern indicates it is global

在 cpp 文件中定义它:

// class1.cpp
#include "header.h"
Array3D array3d;

然后在您想要使用它的任何位置包含标题。

// main.cpp
#include "header.h"
int main()
{
array3d[3][2][1] = 42; 
} 

我不确定我是否理解了您的确切含义,而只是:

class1 obj1;
obj1.array[i][j][k] // assuming you make the array public and already initialized in the constructor(and dont forget to delete it in the destructor)