• 优先队列总结


      最近用了几次优先队列,感觉有必要总结一下队列和优先队列。

    queue

    C++队列是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构。
    1.back() 返回一个引用,指向最后一个元素
    2.empty() 如果队列空则返回真
    3.front() 返回第一个元素
    4.pop() 删除第一个元素
    5.push() 在末尾加入一个元素
    6.size() 返回队列中元素的个数

    priority queue

    优先队列在头文件#include <queue>中;

    其声明格式为:priority_queue <int> 1;//声明一个名为1的整形的优先队列

    基本操作有:

    empty( )  //判断一个队列是否为空

    pop( )  //删除队顶元素

    push( )  //加入一个元素

    size( )  //返回优先队列中拥有的元素个数

    top( )  //返回优先队列的队顶元素

    队列和优先队列有些成员函数是不同,就比如说队列取队首元素用的是front函数,而优先队列用的是top函数.

    #include<stdio.h>//板子
    #include<queue>
    #include<bits/stdc++.h>
    using namespace std;
    struct node//优先队列里的元素为node型
    {
        int x, y;
        node(int xx=0,int yy=0)
        {
            x=xx;
            y=yy;
    
        }
        friend   bool operator < (node a, node b)
        {
            return a.x > b.x;//结构体中,x小的优先级高
        }
    };
    struct number
    {
        int x;
        number(int xx=0)
        {
            x=xx;
        }
        friend bool operator <(number a,number b)//一定要用friend,不然会编译错误
        {
            return a.x>b.x;
        }
    };
    
    int main()
    {
        cout<<"优先队列1"<<endl;
        priority_queue<node>q1;
        while(!q1.empty()) q1.pop();
        q1.push(node(100,1));
        q1.push(node(99,2));
        q1.push(node(10,3));
        q1.push(node(1,4));
        while(!q1.empty())
        {
            node tmp=q1.top();
            q1.pop();
            cout<<tmp.x<<"  "<<tmp.y<<endl;
    
        }
        cout<<"优先队列2"<<endl;
        priority_queue<number>q2;
        while(!q2.empty()) q2.pop();
        q2.push(number(3));
        q2.push(number(30));
        q2.push(number(39));
        q2.push(number(0));
        q2.push(number(1));
        while(!q2.empty())
        {
            number tmp=q2.top();
            q2.pop();
            cout<<tmp.x<<endl;
    
        }
        return 0;
    }
    

  • 相关阅读:
    测试文件报告
    Bug Variations
    阶段一 问答题2
    阶段一 问答题1
    HeapSort
    Git系列 (01):git clone 速度太慢解决方法
    ES6系列 (03):链判断运算符和Null 判断运算符
    ES6系列 (02):解构赋值
    ES6系列 (01):箭头函数this指向问题
    我忘却了所有,抛却了信仰,舍弃了轮回,只为,那曾在佛前哭泣的玫瑰,早已失去旧日的光泽。
  • 原文地址:https://www.cnblogs.com/eason9906/p/11754999.html
Copyright © 2020-2023  润新知