昨晚做了一个题目,试着用优先队列方法求解,根据题意重载了运算符<。结果不对?又试了在集合中使用重载的运算符<,没有问题。郁闷中……后来才发现在优先队列中条件要根据题意取反的。operator重载在结构集合与队列中是必要的,但也要注意区别。可以运行下面代码作个比较。
#pragmawarning(disable:4786)
#include<iostream>
#include<set>
#include<queue>
usingnamespacestd;
constintN=10;
structMsg
...{
intindex;
intprior;
//<operatoroverload
//Itisconsistentinset,butoppositeinpriority_queue
booloperator<(Msgm)const
...{
if(prior==m.prior)
returnindex<m.index;
else
returnprior<m.prior;
}
};
voidrun()
...{
set<Msg>s;
for(inti=1;i<=N;i++)
...{
Msgt;
t.index=i;
t.prior=(N-i)%3+1;
s.insert(t);
}
cout<<"inset: ";
for(set<Msg>::iteratorit=s.begin();it!=s.end();it++)
cout<<(*it).index<<""<<(*it).prior<<endl;
priority_queue<Msg>q;
for(intj=1;j<=N;j++)
...{
Msgt;
t.index=j;
t.prior=(N-j)%3+1;
q.push(t);
}
cout<<" inpriority_queue: ";
while(q.empty()==false)
...{
Msgt=q.top();
cout<<t.index<<""<<t.prior<<endl;
q.pop();
}
}
intmain()
...{
run();
return0;
}
本文通过一个实例探讨了在C++中如何正确使用运算符重载来实现优先队列的功能,并对比了其与集合中重载运算符的区别。通过对代码的分析,展示了在不同容器中使用相同的运算符重载时可能出现的问题及解决方案。
735

被折叠的 条评论
为什么被折叠?



