What am I doing wrong here?
一些不同的事情,包括导致您崩溃的错误。看到我的评论如下。
#include <vector>
// Never, ever, say "using namespace std;" even if (especially if) your textbook says to.
// using namespace std;
using std::vector;
class Node {
private:
int data;
public:
// Prefer to define small functions in-class so that they are automatically inline
// Prefer initialization list to assignment. This is mostly style in your case, but
// does matter in more complex cases.
Node(int d) : data(d) {}
// ~Node();
};
class Heap {
private:
vector<Node> heapVec;
// int currentsize; "currentsize" is redundant, and thus error-prone.
// heapVec always knows what size it is, so just ask it whenever you need to know.
public:
// In this trivial example, with currentsize gone, you don't need any constructor.
// Heap();
// ~Heap();
void insert(int);
void extractMin();
void reduceKey();
};
void Heap::insert(int d) {
// This is your crash bug -- std::vector::operator[] doesn't automatically extend
// the size of the vector (unlike, say, std::map::operator[], which does).
// Also, your use of "new" here is unconventional, and buggy. You have a memory leak.
// It is possible to write perfectly useful C++ programs while never invoking "new"
// directly.
// heapVec[currentsize] = *(new Node(d));
// currentsize++;
// Instead, use std::vector::push_back() or std::vector::insert(), *and* don't call
// new.
heapVec.push_back(Node(d));
}
int main() {
// In this example (and, I bet, in your real-world program), you don't need "new"
Heap h;
h.insert(10);
}
代码'*(new Node(d))'完全错误。它分配Node类的对象,并忘记了指针。这是内存泄漏的定义。您必须更改'vector heapVec;'向'vector heapVec;'或使用类似'boost :: ptr_vector heapVec;'的东西。 –
Arpegius
请勿使用矢量。您很可能最终会发生内存泄漏,因为您将不得不手动删除每个向量成员。 只要做,Dani在下面说,你很好。 –
Ben
+1,用于演示您遇到的问题的完整,最简单的程序。请参阅http://sscce.org为什么这是有价值的原因。 –