我基本上打算创建一个min heap和一些方法,比如remove min和insert。
当我用类的对象调用方法时,方法工作正常。但是,当我决定使用指针时,整个程序在开始时崩溃。
class TreeNode {
private:
TreeNode *left;
TreeNode *right;
unsigned frequency;
unsigned char val;
public:
TreeNode *getLeft() { return left; }
TreeNode *getRight() { return right; }
TreeNode(unsigned char val, unsigned int frequency) {
left = NULL;
right = NULL;
this->frequency = frequency;
this->val = val;
}
unsigned getFrequency() { return frequency; }
signed int setFrequency(int i) { this->frequency = i; }
unsigned char getVal() { return val; }
};
class MinHeap {
private:
int n;
vector<TreeNode *> holder;
public:
MinHeap() {
n = 0;
TreeNode *sentinel;
sentinel->setFrequency(-100);
holder.push_back(sentinel);
}
void insert(TreeNode *val) {
n++;
holder.push_back(val);
restoreUp(n);
}
int getSize(); // returns size of heap
~MinHeap() {}
void restoreUp(int b) {
int k = holder.at(b)->getFrequency();
TreeNode *newVal = holder.at(b);
int iParent = floor(b / 2);
while (holder.at(iParent)->getFrequency() > k && iParent > 0) {
// std::swap(holder.at(b), holder.at(iParent));
// cout<<iParent<<endl;
holder.at(b) = holder.at(iParent);
b = iParent;
iParent = floor(b / 2);
}
holder.at(b) = newVal;
}
TreeNode *removeMin() {
if (n == 0) {
cout << "empty heap" << endl;
return 0;
} else if (n == 1) {
// cout<<n<<endl;
return holder.at(1);
} else if (n == 2) {
if (holder.at(1)->getFrequency() > holder.at(2)->getFrequency()) {
return holder.at(2);
}
return holder.at(1);
} else {
TreeNode *minValue = holder.at(1);
holder.at(0) = holder.at(n - 1);
n--;
restoreDown(1);
return minValue;
}
}
void restoreDown(int i) {
TreeNode *node = holder.at(1);
// int i = 1;
int k = node->getFrequency();
int leftIndex = 2 * i, rightIndex = (2 * i) + 1;
while (rightIndex >= n) {
if (k <= holder.at(leftIndex)->getFrequency() &&
k <= holder.at(rightIndex)->getFrequency()) {
holder.at(1) = node;
return;
}
}
}
};
int main(int argc, char **argv) {
TreeNode *ttn = new TreeNode('t', frequency_table[uint8_t('t')]);
/*MinHeap mh;
mh.insert(ttn); This one works fine*/
// but the next line crashes my code
MinHeap *mh = new MinHeap();
mh->insert(ttn);
}
这是一个特别的问题,因为测试用例使用指针而不是对象。对此有一个简单的纠正吗?
答案 0 :(得分:0)
崩溃与将类用作普通对象或通过指针无关。在任何一种情况下,程序都有未定义的行为。
使用调试器时,首先要看到的是,构造函数内的setFrequency
调用是一个名为sentinel
的未初始化指针
MinHeap() {
n = 0;
TreeNode *sentinel; // not initialized
sentinel->setFrequency(-100); // used
holder.push_back(sentinel);
}