zoukankan      html  css  js  c++  java
  • 7-26 Windows消息队列 (25分)--优先队列

    参考:

    优先队列priority_queue 用法详解

    7-26 Windows消息队列 (25分)

    优先队列比较函数的三种写法

    首先定义结构体node,用来存储消息的名字和优先级,而因为node之间不能直接进行比较,所以重载<使node之间能相互比较(不能对>进行重载因为标准库默认使用<来确定元素的优先级)。

    结构体定义:

    struct  node 
    {
        char s[15];
        int n;
        bool operator < (const struct node& a)
        {
            return n>a.n;//从小到大排序
            //return n<a.n; 从大到小排序
        }
    };
    //或者
    struct node
    {
        char s[15];
        int n;
        bool operator < (struct node a, struct node b)
        {
            return a.n > b.n;
        }
    };

    优先队列定义与头文件:

    #include <queue>
    
    priority_queue<struct node> q;

    代码:

    //AC
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <queue>
    #include <cstdio>
    using namespace std;
    struct node
    {
        char s[15];
        int n;
        bool operator <(const struct node &a) const {return n > a.n;}}t_node;   
    //重载>号会编译出错,因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
    //而且自定义类型的<操作符与>操作符并无直接联系
    int main()
    { 
        int n;
        scanf("%d",&n);
        priority_queue<struct node> q;
        for(int i=0; i<n; i++)
        {
            char order[4]; 
            scanf("%s",order);
            if(order[0] == 'P')
            {
                scanf("%s%d",t_node.s,&t_node.n);//顺序不能反,题目中先输入字符串
                q.push(t_node); 
            }
            else
            {
                if(q.empty())
                    printf("EMPTY QUEUE!
    ");
                else
                {
                    printf("%s
    ",q.top().s);
                    q.pop();
                }
            }
        }
        return 0;
    }
  • 相关阅读:
    网络并发服务器设计
    linux脚本编程技术
    守护进程学习
    UDP通讯程序设计
    TCP通讯程序设计
    linux中socket的理解
    linux网络协议
    kafka ProducerConfig 配置
    crontab定时执行datax
    crontab
  • 原文地址:https://www.cnblogs.com/2020R/p/12476944.html
Copyright © 2011-2022 走看看