重载<在集合set与优先队列priority_queue中的不同

昨晚做了一个题目,试着用优先队列方法求解,根据题意重载了运算符<。结果不对?又试了在集合中使用重载的运算符<,没有问题。郁闷中……后来才发现在优先队列中条件要根据题意取反的。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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值