using namespace std;//Counting methodsint *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 structstruct 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);}
程序首先输出带有出现次数的字符.看起来很好:
: 4A: 2E: 2I: 3S: 6T: 1U: 1Y: 2
peek: Y2peek: U1peek: S6peek: T1peek: I3peek: E2peek: 4peek: A2
这不是预期的顺序.为什么?
解决方法 优先级队列中的元素是指针.由于您没有提供带有2个指向Node对象的函数,因此默认比较函数会比较2个指针.bool compareNodes(Node* val1,Node* val2){ return val1->occurence < val2->occurence;}priority_queue<Node*,vector<Node*>,compareNodes > pq;
您的 *** 作符< Node与Node *比较时使用
总结以上是内存溢出为你收集整理的c – 优先级队列错误的顺序全部内容,希望文章能够帮你解决c – 优先级队列错误的顺序所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)