模拟window Message Queue 消息队列 算法

本文介绍了一个使用C++实现的优先级队列示例,通过自定义消息结构体并重载比较操作符来确保队列按消息的优先级进行排序。文章展示了如何向队列中添加元素及移除最高优先级的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.    }  

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值