模拟window Message Queue 消息队列 算法

来源:互联网 发布:淘宝举证在哪里 编辑:程序博客网 时间:2024/05/24 15:42
Code:
  1. #include <iostream>  
  2. #include <queue>  
  3.   
  4. using namespace std;  
  5.   
  6. struct Message{  
  7.    char Name[100];  
  8.    int Data;  
  9.    int Priority;  
  10.    bool operator < (const Message &a)const  
  11.    {  
  12.        return a.Priority < Priority;  
  13.    }  
  14. };  
  15. priority_queue<Message> v;  
  16. int main(int argc,char* argv[])  
  17. {  
  18.   
  19.     char command[100];  
  20.     Message message ;  
  21.     while(scanf("%s",command)!=EOF)  
  22.     {  
  23.         if(strcmp(command,"GET")==0)  
  24.         {  
  25.             if(v.size()==0)  
  26.             {  
  27.                 printf("EMPTY QUEUE!");  
  28.             }  
  29.             else{  
  30.                printf("%s,%d",v.top().Name,v.top().Data);  
  31.                v.pop();  
  32.             }  
  33.         }  
  34.         else if(strcmp(command,"PUT")==0)  
  35.         {  
  36.             scanf("%s%d%d",&message.Name,&message.Data,&message.Priority);  
  37.             v.push(message);  
  38.         }  
  39.     }  
  40.     return 0;  
  41. }  

测试结果为:

 

Code:
  1. GET  
  2. EMPTY QUEUE!  
  3. PUT msg1 10 5  
  4. PUT msg2 10 4  
  5. GET  
  6. msg2,10  
  7. GET  
  8. msg1,10  
  9. GET  
  10. EMPTY QUEUE!  

 重载操作符的 定义方法为:

Code:
  1. bool operator < (const Message &a)const  
  2.    {  
  3.        return a.Priority < Priority;  
  4.    }  

 

原创粉丝点击