反转优先级队列中元素的顺序
Reversing order of elements in a priority Queue
我把东西推到一个优先级队列中,我为进去的元素做了一个比较方法,当我检查顺序时,我意识到我想让元素以相反的方式进入,所以我把比较方法中的所有布尔返回值都改成了原来的值,现在它给了我一百万个断言失败。如果忽略它们,程序仍然可以按预期工作,但是为什么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);
}
相关文章:
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 序列容器 - 只能按顺序访问元素
- 如何检查 2 个 c++ 数组在 O(1) 或 O(log n) 时间复杂度中是否相同(所有元素都相同,顺序很重要)?
- 保留从一个多集复制到另一个多集的元素的顺序
- 如何在 C++ 中将从文本文件中读取的元素推送和弹出到数组中,并按 Revserse 顺序输出堆栈?
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- 编写链接函数的更短/更有效的方法,该函数按字典顺序添加新元素
- stable_sort不遵守元素的顺序
- 从容器中获取随机元素,该容器在恒定时间内没有严格的元素顺序
- 如何在默认和二维数组中找到顺序扩大元素的位置
- 多重映射是否保证广告顺序与其初始值设定项中给出的元素顺序匹配
- 调用std::nth_element后第n个元素之前的元素顺序
- 如何从向量中删除随机元素而不重复它们并保持元素顺序?C++
- 如何在不更改元素顺序的情况下合并两个unordered_maps
- b树实现中的元素顺序错误
- 提升::p tr_向量改变元素顺序
- Equal_range c++元素顺序
- std::unordered_multimap中的元素顺序