我正在 C 中處理霍夫曼代碼實作,但是在構造程序中,將指標推送到類指標的優先級佇列會導致以下幾種型別的 valgrind 錯誤:
==1158== at 0x40508E: void std::__push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, Node*, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, long, Node*, nodeCompare) (stl_heap.h:182)
==1158== by 0x4034B5: void std::push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, nodeCompare) (stl_heap.h:221)
==1158== by 0x4027AB: std::priority_queue<Node*, std::vector<Node*, std::allocator<Node*> >, nodeCompare>::push(Node* const&) (stl_queue.h:499)
==1158== by 0x40177A: HuffmanCode::HuffmanCode(std::map<char, int, std::less<char>, std::allocator<std::pair<char const, int> > >) (huffmanCodes.cpp:117)
==1158== by 0x401F78: main (huffmanCodes.cpp:188)
==1158== Uninitialised value was created by a stack allocation
==1158== at 0x404EF3: void std::__push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, Node*, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, long, Node*, nodeCompare) (stl_heap.h:178)
這是我認為與該問題相關的代碼:
struct nodeCompare{
bool operator()(Node const& n1, Node const& n2){
return n1.getFreq() > n2.getFreq();
}
};
// huffman code constructor, takes in character frequency map
HuffmanCode::HuffmanCode(map<char, int> m){
// creates priority_queue, creates leafs and adds them to the queue
priority_queue<Node*, vector<Node*>, nodeCompare> PQ;
for(auto item: m){
Node* temp = new Node(item.first, item.second, true);
PQ.push(temp); // causes error
}
// builds rest of tree upward until there is only a single element left (the root)
while(PQ.size() > 1){
Node* temp = new Node(false);
Node* left = PQ.top(); // causes error
PQ.pop();
Node* right = PQ.top();
PQ.pop();
temp->setLChild(left);
temp->setRChild(right);
temp->setFreq(left->getFreq() right->getFreq());
PQ.push(temp); // causes error
}
專案中下面還有更多代碼,但我認為這是導致問題的原因。任何幫助/見解將不勝感激。
uj5u.com熱心網友回復:
應該在 nodeCompare 中使用指標
struct nodeCompare{
bool operator()(Node* n1, Node* n2){
return n1->getFreq() > n2->getFreq();
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/331763.html
上一篇:std::priority_queue如何完成O(logn)插入?[復制]
下一篇:撰寫DbContext擴展方法
