我創建了一個程序,該程序迄今爲霍夫曼編碼程序創建了一個二叉樹節點。由於某種原因,當調試器到達測試兩個孩子是否等於Null的地步(因此在樹上有一個實際的字符而不僅僅是一個父對象)時,程序會凍結。代碼是由包含兩個成員變量的代碼結構組成的每個對象的代碼數組。C++在測試成員變量是否等於NULL時凍結。
void Huff::traverse(Node* root, vector<Code>* code, string code_base){
if(root->childL == NULL && root->childR == NULL){ //stops here
Code c;
c.content = root->litteral;
c.symbol = code_base;
code->push_back(c);
}else{
if (root->childL != NULL)
traverse(root->childL, code, code_base + '0');
if (root->childR != NULL)
traverse(root->childR, code, code_base + '1');
}
}
這就要求這一個功能(這就是所謂的接近尾聲):
vector<Code>* Huff::compress(){
//-------GETTING WEIGHTS/FREQUENCIES------
vector<Node *>* nodes = new vector<Node*>; // Vector of nodes for later use
map<char, int>* freq = new map<char, int>; // Map to find weight of nodes
for(unsigned int i = 0; i < content.length(); i++)
(*freq)[content[i]]++;
CopyTo copyto(nodes); //sets vector<Node*> to copy to
for_each(freq->begin(), freq->end(), copyto); // Copies
delete freq;
vector<Node *>::iterator beg = nodes->begin();
//-------SETTING UP TO BUILD TREE------
if(nodes->size() % 2 == 1){ //makes sure there are an even number of nodes
Node* fill = new Node;
fill->set_node(0, '*', NULL, NULL);
nodes->push_back(fill);
}
huff_sort(nodes); // sort nodes by weight
//-------BUILDING TREE------
while(nodes->size() != 1){ //Sorts nodes by weight and then removes two of them and replaces them with one
int w= (**beg).weight + (**(beg+1)).weight;
Node* p = new Node;
p->set_node(w, '*', *nodes->begin(), *(nodes->begin()+1)); //making it the parent node of the two lowest nodes
nodes->erase(nodes->begin(), nodes->begin()+2);
unsigned int i = 0;
while(w > (*nodes)[i]->weight && i <= nodes->size()){ //finds where to insert the parent node based on weight
i++;
}
if(i > nodes->size()) //if it needs to be inserted at the end
nodes->push_back(p);
else
nodes->insert(nodes->begin()+i, p);
delete p;
}
//-------TRAVERSING TREE------
Node* root = (*nodes)[0];
delete nodes;
vector<Code>* codes;
traverse(root, codes , "");
delete root;
return codes;
}
注:代碼遍歷樹塊,其中樹被創建之前while循環
我看不到會導致程序凍結的行。我認爲需要更多信息。你沒有訪問調試器嗎? – 2012-07-24 17:41:03
根是否有效?我可能不會說。 – 2012-07-24 17:42:49