如何使用模板在CPP中分配3D数组
How to allocate 3D array in CPP using template
我想写一个模板类为任何类型的变量分配3D数组。下面的代码是我尝试过的:
class Alloc3D{
public:
template <class T>
static T*** Alloc(int w, int h, int d);
};
template <class T>
T*** Alloc(int w, int h, int d)
{
T *** field = new T **[w+1];
for( int i=0; i<w; i++ ) {
field[i] = new T*[h+1];
for( int j=0; j<h; j++ ) {
field[i][j] = new T[d];
}
field[i][h] = NULL;
}
field[w] = NULL;
return field;
}
然而,当我调用这个函数为:
int*** k = Alloc3D::Alloc<int>(nX_, nY_, nZ_);
它不工作。
我的问题是,我不能使用这种风格来分配3D数组的任何类型的变量?如果我只使用一个函数而不是类,模板将工作得很好。
在定义Alloc
函数时缺少类名:
声明:
template <class T>
static T*** Alloc(int w, int h, int d);
定义:
template <class T>
T*** Alloc3D::Alloc(int w, int h, int d) {}
这是因为您只声明 Alloc3d::Alloc
函数。您定义了一个全局函数Alloc
虽然这不是您问题的解决方案,但我想为您喜欢做的事情提出另一种实现:
template<typename Ty>
class Grid3D
{
public:
Grid3D(int w, int h, int d)
: w_(w), h_(h), d_(d), p_(w*h), cells_(w*h*d)
{
}
Ty& at(int x, int y, int z) { return cells_[p_*z + w_*y + x]; }
const Ty& at(int x, int y, int z) const { return cells_[p_*z + w_*h + x]; }
private:
typename std::vector<Ty> cells_;
int w_, h_, d_, p_;
};
int main(int argc, char* argv[])
{
Grid3D<float> g(4, 5, 6);
g.at(2, 3, 4) = 3.14159f;
// ...
}
相关文章:
- 将数组的地址分配给变量并删除
- vector.resize()中的分配错误
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- Win32编译器选项和内存分配
- 函数中堆分配的效果与缺少堆分配的情况
- 无法将结构注册为增强几何体3D点
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 获取字符串的长度并将其分配给数组
- 将地址分配给本地指针后,公共对象的变量将消失
- OpenGL大的3D纹理(>2GB)非常慢
- 除非同时构造,否则无法在 3D 地图中分配值
- 将分配给一个3D阵列
- C++:解除分配 3D 矢量
- 动态分配 3D 阵列
- 动态分配 3D 数组的内存,该数组使用最小内存,并且在 C++ 中以连续形式
- 如何使用模板在CPP中分配3D数组
- 使用一个动态分配的内存块创建2d或3d数组
- 如何在c++中使用calloc为3D数组分配内存
- 如何重新分配/调整3d数组的大小以适应新的大小