在优先队列中使用结构体的若干小结

来源:互联网 发布:韩国工业 知乎 编辑:程序博客网 时间:2024/06/05 19:44

以结构体Time为例:

[cpp] view plain copy
  1. struct Time{  
  2.     int start, end;
  3. };  


使用优先队列时,如果需要对Time中的start从小到大排序,有两种方法:

[cpp] view plain copy
  1. priority_queue<Time> pq;  


一.在结构体外重载结构体小于运算符:
[cpp] view plain copy
  1. bool operator <(const Time& a,const Time& b){  
  2.     return a.start > b.start;  
  3. }  //这里以大于重载小于是因为默认情况下,优先队列是以大的作为队首,这样一反,就可以再默认情况下使得小的作为队首  

二.直接在结构体中重载小于运算符:
[cpp] view plain copy
  1. struct Time{    
  2.     int start, end;    
  3.     bool operator < (const Time& t)const{    
  4.         return start > t.start;    
  5.     }    
  6. };    

实质上来说是一样的。。。。

另外要注意的是:参数列表中的const不能省略,否则报错~~


出处:http://blog.csdn.net/catglory

原创粉丝点击