如何调整动态模板数组的大小

How do you resize a dynamic template array?

本文关键字:数组 动态 何调整 调整      更新时间:2023-10-16

我有一个动态模板数组作为我的类的成员。但是,我不能在构造函数或任何其他函数中调整数组的大小。我对语法感到困惑。下面是代码:

template <class Type> class MaxHeapTree {
private:
    HeapNode<Type> *array[];
    HeapNode<Type> *root;
    int elementSize;
    int height;
    int leafCounter;
public: 
    // Constructor
    MaxHeapTree(int n = 10) : elementSize(0), height(0), leafCounter(0) {
        HeapNode<Type> *array = new HeapNode<Type>[n];
    }

该数组是HeapNode类中包含的HeapNode<Type>对象的数组。下面是HeapNode类的构造函数:

template <class Type> class HeapNode {
private:
    int key;
    Type value;
public:
    HeapNode(int key, Type const &value) {
        this->key = key;
        this->value = value;
    }

显示的代码有多个问题。

HeapNode<Type> *array[];
如前所述,这应该简单地声明为:
HeapNode<Type> *array;
然后,在构造函数中:
HeapNode<Type> *array = new HeapNode<Type>[n];

在构造函数中声明了一个名为"array"的变量。这绝对不会初始化该名称的类成员。构造函数应该是:

MaxHeapTree(int n = 10) : array(new HeapNode<Type>[n]), elementSize(0),
                          height(0), leafCounter(0)
{
}

可以推测,数组的大小n也应该存储在某个地方。但这部分在问题中没有显示。

此外,我还会质疑在这里使用动态分配的必要性。我在这里没有看到不能通过使用std::vector来代替动态分配的数组来完成的东西。现代c++代码很少需要newdelete任何东西,特别是数组。在大多数情况下,标准c++容器消除了动态分配的需要。如果从一开始就在这里使用std::vector,那么这个问题就不会发生。

使用容器来管理:

std::vector<HeapNode<Type>> array