实现此自定义priority_queue的正确方法是什么

What is the correct way of implementing this custom priority_queue

本文关键字:方法 是什么 queue 自定义 priority 实现      更新时间:2023-10-16

我想建立一个对象的优先级队列,该队列具有三个具有我自己的比较器的元素。我尝试了以下代码,但显示错误.


#include<bits/stdc++.h>
using namespace std;

class triplet {
public:    
int data;
int arr;
int index;       
};
bool compare( triplet x, triplet y ){
if(x.data < y.data){
return true;
}
else{
return false;
}
}
int main(){
priority_queue<triplet,vector<triplet>,compare> pq1;
}

收到以下错误 在此处输入图像描述

如果两个元素相等,则比较例程必须返回 false,但您的版本返回 true。

试试这个

bool compare(triplet x, triplet y) {
if (x.data < y.data) {
return true;
}
else {
return false;
}
}

或者像这样让它更简单一点

bool compare(triplet x, triplet y) {    
return x.data < y.data;
}

但重要的一点是<不是<=.

编辑

您的代码也不正确地使用了comparecompare不是一种类型,因此它不是 priority_queue 模板的有效参数。

compare的类型是bool (*)(triplet, triplet),因此正确的方法是在模板中使用该类型并将实际的比较函数传递给构造函数。喜欢这个

priority_queue<triplet, vector<triplet>, bool (*)(triplet, triplet)> pq1(compare);

顺便说一句,通常您会通过创建比较函子而不是函数来做到这一点。这样更干净(并且可能更有效(。