【问题标题】:Anomaly in Priority Queue Custom Sort in C++C ++中优先级队列自定义排序中的异常
【发布时间】:2021-07-08 10:36:46
【问题描述】:

我浏览了几篇关于 C++ 中自定义排序优先级队列的 StackOverflow 和 Codeforces 文章。默认情况下,C++ 实现是 MaxHeap ,因此它会以降序输出元素。我添加greater<int> 的小调整会上升。我使用自己的比较器功能进行了尝试,如下所示:

#include<bits/stdc++.h>
using namespace std;
class comp{
    public:
bool operator()(const int &a,const int &b){
        return a>b;
    }
};
int main(){
    priority_queue<int,vector<int>,comp> pq;
    pq.push(5);
    pq.push(1);
    pq.push(8);
    while(!pq.empty()){
        cout<<pq.top()<<" ";
        pq.pop();
    }
    return 0;
}

这给出了预期的输出:1 5 8

但如果我将其更改为:

#include<bits/stdc++.h>
using namespace std;
class comp{
    public:
bool operator()(const int &a,const int &b){
        if(a>b)
            return true;
    }
};
int main(){
    priority_queue<int,vector<int>,comp> pq;
    pq.push(5);
    pq.push(1);
    pq.push(8);
    while(!pq.empty()){
        cout<<pq.top()<<" ";
        pq.pop();
    }
    return 0;
}

输出变为:8 1 5

我不知何故无法得到这个,非常感谢任何帮助。

【问题讨论】:

  • 开启编译器警告并注意
  • @463035818_is_not_a_number 是的,我做到了,函数到达非空的末尾,即没有返回值,谢谢。

标签: c++ queue priority-queue minmax-heap


【解决方案1】:

我建议您阅读编译器警告...如果a&lt;=b 没有返回语句...您将看到bool operator()(const int &amp;a,const int &amp;b)...这是未定义的行为

您应该这样做:

#include<bits/stdc++.h>
using namespace std;
class comp{
    public:
    bool operator()(const int &a,const int &b){
        if(a>b)
            return true;
        /* else */ return false;
    }
};
int main(){
    priority_queue<int,vector<int>,comp> pq;
    pq.push(5);
    pq.push(1);
    pq.push(8);
    while(!pq.empty()){
        cout<<pq.top()<<" ";
        pq.pop();
    }
    return 0;
}

【讨论】:

  • 或者只是return a &gt; b; 不需要if (condition) return true; else return false;
  • @463035818_is_not_a_number 是肯定的,但这是 OP 发布的第一个片段......所以我想他想使用 if
  • @AlbertoSigigaglia d'oh。我认为两者之间的区别是&lt;&gt;。误读
  • @AlbertoSinigaglia 这就像一个魅力,函数必须返回一个 bool ,它不是,谢谢。是的,我想使用if,因为我将来可能会遇到一些自定义结构或类。
猜你喜欢
  • 2012-03-03
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
  • 2020-03-26
相关资源
最近更新 更多