第二次推送时具有自定义比较器分段错误的优先级队列 [英] Priority queue with custom comparator segmentation fault when pushing second time
问题描述
我正在使用 priority_queue
,这是代码:
I'm using a priority_queue
, this is the code:
typedef vector<int> state;
typedef bool (*comp)(const state&, const state&);
typedef priority_queue<state, vector<state>, comp> prioq;
prioq prio;
我使用的是自定义比较器,定义在这里:
I'm using a custom comparator, that is defined here:
bool comparator (const state& a , const state& b) {
return a[0] < b[0];
}
我可以推送第一种状态,但是当我尝试推送第二种状态时,会出现分段错误:11.
I can push the first state, but when I try to push the second, I get a segmentation fault: 11.
我不知道比较器是否正确,我也不知道如何创建自定义比较器.我正在尝试按每个州的第一个数字对 priority_queue
进行排序.
I don't know if the comparator is right, I don't know really much how to create a custom comparator. I'm trying to order the priority_queue
by the first number of each state.
推荐答案
prioq prio;
使用默认构造的比较器(类型为 comp
)构建优先级队列案件).这意味着内部存储的指向比较函数的指针实际上是用零初始化的.可以将比较器(如果没有默认构造的比较器)初始化为作为构造函数的参数传递的值:
prioq prio;
constructs a priority queue with a default-constructed comparator (of type comp
in your case). This means that the internally stored pointer to a comparing function is actually initialized with zero. A comparator (if a default constructed one is not enough) can be initialized to a value passed as a constructor's argument:
prioq prio(&comparator);
// ~~~~~~~~~~^
这篇关于第二次推送时具有自定义比较器分段错误的优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!