Assertion error on priority queue with custom class pointers
I'm implementing a A* search algorithm but I keep running into problems with the priority queue. I have implemented a custom comparator for the priority queue according to this article
This is the relevant code:
class CNode;
struct CompareNode : public binary_function<CNode*, CNode*, bool> {
bool operator()(const CNode* lhs, const CNode* rhs) const {
return lhs->m_costFromStart+lhs->m_heuristic > rhs->m_costFromStart+rhs->m_heuristic;
}
};
bool AStarSearch(CNode* start, CNode* end) {
priority_queue<CNode*, vector<CNode*>, CompareNode> open;
...
}
Call stack:
std::_Debug_heap ...
std::pop_heap ...
std::priority_queue<CNode *,std::vector<CNode *,std::allocator<CNode *> >,Compar开发者_如何学GoeNode>::pop()
AStarSearch(CNode * start=0x0f9a23b8, CNode * end=0x0f9a24e8)
Greater then was used as I needed a min heap for this algorithm. The implementation seems to work fine and the problem goes away when it is run in release mode but the priority queue occasionally throws "Invalid heap" assertion failures in debug mode when the priority queue is pop()ed.
I'm not familiar with binary_function in stl but the problem seems to lie with the comparator. Removing the comparator or changing the sign to less then removes the error but that would give me a max heap. Is there something I'm missing?
Thanks for the help. Turns out I did not rebuild the heap after changing the cost of nodes in the priority queue. Calling
make_heap(const_cast<CNode**>(&open.top()), const_cast<CNode**>(&open.top()) + open.size(),
CompareNode());
after every modification to the pq solved the problem.
精彩评论