我把东西推到一个优先级队列中,我为进去的元素做了一个比较方法,当我检查顺序时,我意识到我想让元素以相反的方式进入,所以我把比较方法中的所有布尔返回值都改成了原来的值,现在它给了我一百万个断言失败。如果忽略它们,程序仍然可以按预期工作,但是为什么assert失败?这个项目为什么要关心这个问题?
bool operator()(charElement &operand1,charElement &operand2)
{
// If the frequency of op1 < op2 then return true
if(operand1.i_frequency < operand2.i_frequency) return true; //change to false
// If the frequency of op1 > op2 then return false
if(operand1.i_frequency > operand2.i_frequency)return false; //change to true
// If the frequency of op1 == op2 then return true (that is priority is indicated to be less even though frequencies are equal)
if(operand1.i_frequency == operand2.i_frequency)return true; //change to false
// By default , return true (that is priority is indicated to be less)
return true; //change to false
}
顺便问一下,为什么我的查询被否决了?我试着问一些合理的问题,我相信这就是其中之一。
details:我将操作符定义更改为@sehe建议的。现在,如果我向返回值添加一个not操作符,它会在include文件(第2457行)内给出断言失败(无效操作符<)。我检查了文件,似乎错误是在一个名为Push_heap_0的内联方法中,但我对该代码的作用感到困惑
你不能简单地把参数的顺序颠倒一下吗?即替换:
bool operator()(charElement &operand1,charElement &operand2)
:
bool operator()(charElement &operand2,charElement &operand1)
然后你可以让函数体保持原样。
另一方面,比较是只读操作,我们应该始终尊重const的正确性:
bool operator()(const charElement& operand2, const charElement& operand1)
另外,如果元素相等,则不允许返回true
:
if(operand1.i_frequency == operand2.i_frequency)return true; // HUGE PROBLEM!
在这种情况下必须始终返回false
,无论您是想要"正常"顺序还是"向后"顺序。
与<
相反的是,而不是 >
,而是>=
。这对于程序员来说似乎很难理解。
问题可能是多方面的
- chareelement .i_frequency是什么类型?
- 你是如何使用dequeue(类型&&构造函数,,算法调用)
也就是说,看起来您可以极大地简化比较器。
bool operator()(charElement &operand1,charElement &operand2)
{
return operand1.i_frequency < operand2.i_frequency;
}
或对于反向逻辑:
bool operator()(charElement &operand1,charElement &operand2)
{
return operand1.i_frequency > operand2.i_frequency;
}
如果它实际上是一个更复杂的化合物:
bool operator()(charElement &operand1,charElement &operand2)
{
return std::tie(operand1.i_frequency, operand1.otherfield) <
std::tie(operand2.i_frequency, operand2.otherfield);
}