【问题标题】:How do you resize a dynamic template array?如何调整动态模板数组的大小?
【发布时间】:2016-07-04 23:44:27
【问题描述】:

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

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&lt;Type&gt; 对象的数组。下面是 HeapNode 类的构造函数:

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

【问题讨论】:

  • 改用std::vector
  • 调整“动态非模板数组”大小的方式相同。

标签: c++ arrays templates dynamic-arrays template-classes


【解决方案1】:

显示的代码存在多个问题。

HeapNode<Type> *array[];

如前所述,应该简单地声明:

HeapNode<Type> *array;

然后,在构造函数中:

HeapNode<Type> *array = new HeapNode<Type>[n];

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

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

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

此外,我什至会质疑这里是否需要使用动态分配。我在这里看不到使用std::vector 代替动态分配的数组无法完成的事情。现代 C++ 代码很少需要 newdelete 任何东西,尤其是数组。在大多数情况下,标准 C++ 容器消除了动态分配的需要。如果一开始就在这里使用std::vector,那么这个问题一开始就不会发生。

【讨论】:

  • 我的任务是使用动态数组创建堆树。但是,我之前尝试过初始化,它不会编译。
  • “它不会编译”不是一个有用的问题描述。
  • MaxHeapTree.h: In instantiation of ‘MaxHeapTree&lt;Type&gt;::MaxHeapTree(int) [with Type = std::__cxx11::basic_string&lt;char&gt;]’: main.cpp:14:61: required from here MaxHeapTree.h:22:98: error: no matching function for call to ‘HeapNode&lt;std::__cxx11::basic_string&lt;char&gt; &gt;::HeapNode()’ xHeapTree(int n = 10) : array(new HeapNode&lt;Type&gt;[n]), elementSize(0), height(0), leafCounter(0)
  • HeapNode.h:14:2: 注意:候选:HeapNode::HeapNode(int, const Type&) [with Type = std::__cxx11::basic_string] HeapNode( int key, Type const &value) { ^ HeapNode.h:14:2: 注意:候选人需要 2 个参数,0 提供 HeapNode.h:9:29: 注意:候选人:HeapNode<:__cxx11::basic_string> >::HeapNode(const HeapNode<:__cxx11::basic_string> >&) 模板 class HeapNode {
  • 这是因为您的HeapNode 类没有默认构造函数。这与数组构造无关。你必须解决这个问题,一个单独的问题,它与MaxHeapTree 完全无关。无论你如何构造一个数组,在MaxHeapTree 的构造函数中,在你修复这个问题之前都是不可能的。
【解决方案2】:

使用容器来管理它:

std::vector<HeapNode<Type>> array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2012-10-02
    • 2013-06-16
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多