昨晚做了一个题目,试着用优先队列方法求解,根据题意重载了运算符<。结果不对?又试了在集合中使用重载的运算符<,没有问题。郁闷中……后来才发现在优先队列中条件要根据题意取反的。operator重载在结构集合与队列中是必要的,但也要注意区别。可以运行下面代码作个比较。
#pragma
warning(disable : 4786)
#include < iostream >
#include < set >
#include < queue >
using namespace std;
const int N = 10 ;
struct Msg
... {
int index;
int prior;
//< operator overload
//It is consistent in set,but opposite in priority_queue
bool operator <(Msg m) const
...{
if (prior==m.prior)
return index<m.index;
else
return prior<m.prior;
}
} ;
void run()
... {
set <Msg> s;
for(int i=1;i<=N;i++)
...{
Msg t;
t.index=i;
t.prior=(N-i)%3+1;
s.insert(t);
}
cout << "in set: ";
for(set <Msg>::iterator it=s.begin();it!=s.end();it++)
cout << (*it).index << " " <<(*it).prior << endl;
priority_queue <Msg> q;
for(int j=1;j<=N;j++)
...{
Msg t;
t.index=j;
t.prior=(N-j)%3+1;
q.push(t);
}
cout << " in priority_queue: ";
while(q.empty()==false)
...{
Msg t=q.top();
cout << t.index << " " <<t.prior << endl;
q.pop();
}
}
int main()
... {
run();
return 0;
}
#include < iostream >
#include < set >
#include < queue >
using namespace std;
const int N = 10 ;
struct Msg
... {
int index;
int prior;
//< operator overload
//It is consistent in set,but opposite in priority_queue
bool operator <(Msg m) const
...{
if (prior==m.prior)
return index<m.index;
else
return prior<m.prior;
}
} ;
void run()
... {
set <Msg> s;
for(int i=1;i<=N;i++)
...{
Msg t;
t.index=i;
t.prior=(N-i)%3+1;
s.insert(t);
}
cout << "in set: ";
for(set <Msg>::iterator it=s.begin();it!=s.end();it++)
cout << (*it).index << " " <<(*it).prior << endl;
priority_queue <Msg> q;
for(int j=1;j<=N;j++)
...{
Msg t;
t.index=j;
t.prior=(N-j)%3+1;
q.push(t);
}
cout << " in priority_queue: ";
while(q.empty()==false)
...{
Msg t=q.top();
cout << t.index << " " <<t.prior << endl;
q.pop();
}
}
int main()
... {
run();
return 0;
}