如何调整动态模板数组的大小
How do you resize a dynamic template array?
我有一个动态模板数组作为我的类的成员。但是,我不能在构造函数或任何其他函数中调整数组的大小。我对语法感到困惑。下面是代码:
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++代码很少需要new
或delete
任何东西,特别是数组。在大多数情况下,标准c++容器消除了动态分配的需要。如果从一开始就在这里使用std::vector
,那么这个问题就不会发生。
使用容器来管理:
std::vector<HeapNode<Type>> array
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结