简体   繁体   English

霍夫曼树制作C ++

[英]Huffman Tree Creation C++

I have a class Node which has Node *left and Node *right as the variables. 我有一个Node类,它的Node * left和Node * right是变量。 Now I have a function to build the huffman tree as follows 现在我有一个功能来构建霍夫曼树,如下所示

int x = pQueue.size();

for(int i=0;i<x-1;i++){

    Node *z = new Node;
    z->left = &pQueue.extractMin();
    z->right = &pQueue.extractMin();
    z->setchar(NULL);
    z->setfrequency(z->left->getFrequency() + z->right->getFrequency());
    pQueue.insert(z);

}

This is the standard function to create huffman tree. 这是创建霍夫曼树的标准功能。 However the problem is this. 但是问题是这样的。 Initially when a new Node* z is created and its left and right child are assigned, during the next execution of the loop the left and right child of z are re assigned, and I am losing the initially assigned values. 最初,当创建新的Node * z并为其左,右子级分配时,在下一次执行循环时,将重新分配z的左,右子级,而我将丢失最初分配的值。 I was under the impression that during each execution of the loop, new object is created and its left and right child will have different memory locations. 我给人的印象是,在每次循环执行期间,都会创建新对象,并且其左,右子对象将具有不同的内存位置。 But this is not happening. 但是,这没有发生。 How do I make a new object each time the loop is executed.?? 每次执行循环时,如何制作新对象??

Here is what I am getting 这就是我得到的

在此处输入图片说明

If you check the node with frequency 14 is assigned some memory locations in the first execution as its left and right children . 如果您检查频率为14的节点,则在第一次执行中为其左,右子级分配了一些存储位置。 however in the next execution the left and right child of frequency 14 node is null and children of frequency 25 node are set to the previous locations. 但是,在下一次执行中,频率14节点的左子级和右子级为空,并且将频率25节点的子级设置为先前的位置。 i expect them to be the same assigned during first round for frequency 14 node and new locations for frequency 25 node. 我希望在第一轮为频率14节点分配新的位置,并为频率25节点分配新的位置。

If, as you said, pQueue is a vector of Node objects (and I'm assuming std::vector - if not, ignore the answer!), by using vector::insert(), you are actually adding an iterator rather than a Node object. 如您所说,如果pQueue是Node对象的向量(并且我假设std :: vector-否则,请忽略答案!),通过使用vector :: insert(),您实际上是在添加迭代器而不是一个Node对象。 Try something like this instead: 尝试这样的事情:

int x = pQueue.size();

for(int i=0;i<x-1;i++){

    Node z;
    z.left = &pQueue.extractMin();
    z.right = &pQueue.extractMin();
    z.setchar(NULL);
    z.setfrequency(z.left->getFrequency() + z.right->getFrequency());
    pQueue.push_back(z);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM