【问题标题】:Priority Queue Wrong Order优先队列错误顺序
【发布时间】:2010-03-03 16:41:36
【问题描述】:

我正在编写霍夫曼编码。这是我的程序的开始:

using namespace std;

//Counting methods
int *CountCharOccurence(string text)
{
    int *charOccurrence = new int[127];
    for(int i = 0; i < text.length(); i++)
    {
        charOccurrence[text[i]]++;
    }
    return charOccurrence;
}

void DisplayCharOccurence(int *charOccurrence)
{
    for(int i = 0; i < 127; i++)
    {
        if(charOccurrence[i] > 0)
        {
            cout << (char)i << ": " << charOccurrence[i] << endl;
        }
    }
}

//Node struct
struct Node
{
    public:
        char character;
        int occurrence;

        Node(char c, int occ) {
            character = c;
            occurrence = occ;
        }

        bool operator < (const Node* node)
        {
            return (occurrence < node->occurrence);
        }
};

void CreateHuffmanTree(int *charOccurrence)
{
    priority_queue<Node*, vector<Node*> > pq;
    for(int i = 0; i < 127; i++)
    {
        if(charOccurrence[i])
        {
            Node* node = new Node((char)i, charOccurrence[i]);
            pq.push(node);
        }
    }

    //Test
    while(!pq.empty())
    {
        cout << "peek: " << pq.top()->character <<  pq.top()->occurrence << endl;
        pq.pop();
    }
}

int main(int argc, char** argv) {

    int *occurrenceArray;
    occurrenceArray = CountCharOccurence("SUSIE SAYS IT IS EASY");
    DisplayCharOccurence(occurrenceArray);
    CreateHuffmanTree(occurrenceArray);

    return (EXIT_SUCCESS);
}

程序首先输出字符及其出现次数。这看起来不错:

 : 4
A2
E:2
我:3
小号:6
电话:1
你:1
Y:2

但必须按优先级顺序显示节点内容的测试循环输出以下内容:

偷看:Y2
偷看:U1
窥视:S6
偷看:T1
偷看:I3
偷看:E2
窥视:4
偷看:A2

这不是预期的顺序。为什么?

【问题讨论】:

    标签: c++ priority-queue huffman-code


    【解决方案1】:

    优先级队列中的元素是指针。由于您没有提供需要 2 个指向 Node 对象的指针的函数,因此默认比较函数会比较 2 个指针。

    bool compareNodes(Node* val1, Node* val2)
    {
       return val1->occurence < val2->occurence;
    }
    priority_queue<Node*, vector<Node*>,compareNodes > pq;
    

    Node 与 Node* 比较时使用您的运算符

    【讨论】:

      【解决方案2】:

      你应该告诉你的优先队列它应该按什么排序。在您的情况下,您必须告诉它按Node::occurence 排序。

      【讨论】:

        【解决方案3】:

        您正在存储指向队列中节点的指针,但没有提供合适的比较函数,因此通过比较指针对它们进行排序。您提供的 operator&lt; 会将节点与指针进行比较,这不是您想要的。

        有两种选择:

        • 提供一个函数,根据它们的值比较两个节点指针,并将这个函数交给队列,或者
        • 将节点对象存储在队列中,并提供operator&lt; 来比较两个节点。

        第二个选项也将修复代码中的内存泄漏,并删除一大堆不必要的内存分配,所以我建议这样做。

        【讨论】:

        • Tnx,它现在可以工作了。我现在编程了一段时间,但我是 C++ 新手。我不得不说,你越了解这门语言,你就越喜欢它。但我认为开始是相当艰难的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-25
        • 1970-01-01
        • 2013-03-16
        • 2012-11-01
        • 1970-01-01
        • 2019-09-18
        • 1970-01-01
        相关资源
        最近更新 更多