如何使用模板在CPP中分配3D数组

How to allocate 3D array in CPP using template

本文关键字:分配 3D 数组 CPP 何使用      更新时间:2023-10-16

我想写一个模板类为任何类型的变量分配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;
    // ...
}