如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
How to declare a global 2d 3d 4d ... array (heap version) variable that could be used in the entire program?
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::array
或std::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)
相关文章:
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 如何在 3D OpenGL 场景上绘制 SDL 2D 矩形?
- 根据组件 1、2(和 3)对空间 (2D/3D) 向量进行排序
- 删除使用 new 创建的 2D 或 3D 指针
- 将 3D 变换转换为 2D
- CUDA,使用2D和3D阵列
- 用于将笛卡尔 (x,y,z) 转换为圆柱坐标 (ρ,θ,z) 坐标 2D/3D 的代码
- 从 C++ 中的 3D 矩阵中提取 2D 矩阵
- 使用 pcl 或 opencv 在 2D 场景中匹配 3D 模型
- 将 2D 图像坐标转换为 z = 0 的 3D 世界坐标
- 将每个对象渲染到空间中,并在3D场景上渲染2D场景
- 使用 2D 数据创建 3D 直方图(OpenCV?
- 使用 OpenCV 在 3D 矩阵中导入 2D 矩阵
- 将 2D 屏幕坐标转换为 3D 世界坐标
- OpenCV从2D像素获取3D坐标
- 使用cuda的平行尺寸降低(3d至2d)
- 数据结构2d/3d瓦片数组C++
- 标准化 2D/3D 矢量/坐标类
- 2d(3d)坐标的哈希映射(即双精度向量)
- 找出4个非共面点的2D-3D对应关系