我正在使用STL优先队列来收集我自己的类Lettura的对象。
//---------LETTURA----------
enum Priority {zero, standard, urgent};
class Lettura{
public:
int valore;
char sensore;
Priority priorita;
Lettura(): valore(0),sensore('\0'),priorita(zero){}
Lettura(const int val, const char s='\0', const Priority p=zero): valore(val),sensore(s), priorita(p){}
friend ostream& operator<<(ostream& out, const Lettura & lett);
};
我希望按照“priorita”降序的顺序弹出它们,但我也希望相同优先级的元素像普通队列一样按FIFO原则弹出。但是实际上,我得到的是随机顺序的相同优先级元素:
top: l5 urgent
top: l1 standard
top: l4 standard
top: l6 standard
top: l2 standard
top: l3 standard
我希望同等优先级的元素能按照先进先出(FIFO)的顺序排列:
top: l5 urgent
top: l1 standard
top: l2 standard
top: l3 standard
top: l4 standard
top: l6 standard
这是我的代码:
int main() {
std::priority_queue<Lettura, std::vector<Lettura>, std::less<Lettura> > coda;
Lettura l1(50,'a',standard);
Lettura l2(50,'b',standard);
Lettura l3(120,'c',standard);
Lettura l4(100,'d',standard);
Lettura l5(30,'e',urgent);
Lettura l6(35,'f',standard);
coda.push(l1);
coda.push(l2);
coda.push(l3);
coda.push(l4);
coda.push(l5);
coda.push(l6);
cout<<"top: "<<coda.top()<<"\n"; coda.pop();
cout<<"top: "<<coda.top()<<"\n"; coda.pop();
cout<<"top: "<<coda.top()<<"\n"; coda.pop();
cout<<"top: "<<coda.top()<<"\n"; coda.pop();
cout<<"top: "<<coda.top()<<"\n"; coda.pop();
cout<<"top: "<<coda.top()<<"\n"; coda.pop();
}
我已经实现了以下比较方法:
bool operator<(const Lettura& l1, const Lettura& l2){
return l1.priorita < l2.priorita;
}
bool operator<=(const Lettura& l1, const Lettura& l2){
return l1.priorita <= l2.priorita;
}
我也尝试了不同的队列构造函数,但没有成功:
std::priority_queue<Lettura> coda;
std::priority_queue<Lettura, std::vector<Lettura>, std::less_equal<Lettura> > coda;
有人能帮助我吗?