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爲什麼這是有價值的原因。 –