zoukankan      html  css  js  c++  java
  • STL优先队列的使用

    STL中有一个优先队列的容器可以使用。

    【头文件】

    queue 队列容器

    vector 向量容器

    【操作】

    优先级队列支持的操作

    q.empty()         如果队列为空,则返回true,否则返回false

    q.size()            返回队列中元素的个数

    q.pop()             删除队首元素,但不返回其值

    q.top()             返回具有最高优先级的元素值,但不删除该元素

    q.push(item)     在基于优先级的适当位置插入新元素

    对于Pascal留下来的手打堆习惯来说,其实对我用处不大,不过好像STL里面的复杂度更低,代码长度也能少点,以后尽量用STL好了。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<queue>
     4 
     5 using namespace std;
     6 
     7 struct cmp
     8 {
     9     bool operator()(int x,int y)
    10     {
    11         return x>y;
    12     }
    13 };
    14 
    15 typedef struct nod
    16 {
    17     int x,y;
    18     friend bool operator < (nod a,nod b)
    19     {
    20         return a.y>b.y;
    21     }
    22 } node;
    23 
    24 int main()
    25 {
    26     priority_queue<int>simple;
    27     priority_queue<int,vector<int>,cmp>define;
    28     priority_queue<node>heap;
    29     
    30     int a[10]={20,50,3202,20,503,12,56,62,50,80};
    31     
    32     printf("Simple Test:
    ");
    33     for (int i=0;i<10;i++) simple.push(a[i]);
    34     for (int i=1;i<=10;i++)
    35     {
    36         int temp=simple.top();
    37         simple.pop();
    38         printf("%d
    ",temp);
    39     }
    40     
    41     printf("Define Test:
    ");
    42     for (int i=0;i<10;i++) define.push(a[i]);
    43     for (int i=1;i<=10;i++)
    44     {
    45         int temp=define.top();
    46         define.pop();
    47         printf("%d
    ",temp);
    48     }
    49     
    50     printf("Heap Test:
    ");
    51     node b[10]={{1,2},{2,100},{3,4},{4,50},{5,6},{6,7},{7,8},{8,9},{9,10},{10,11}};
    52     for (int i=0;i<10;i++) heap.push(b[i]);
    53     for (int i=1;i<=10;i++)
    54     {
    55         node temp=heap.top();
    56         heap.pop();
    57         printf("%d %d
    ",temp.x,temp.y);
    58     }
    59     
    60     printf("%d",2<1);
    61     
    62     return 0;
    63 }
    Do Cool Things That Matter!
  • 相关阅读:
    TIDB-存储
    MySQL的ACID
    MySQL MVCC
    MySQL 悲观锁、乐观锁、MVCC一
    MySQL写放大总结
    基于Linux上的wifi密码爆破
    Stack与Queue的实现(c++模板实现)
    vector 实现二维数组
    Linux下的静态链接与动态链接
    260. Single Number III
  • 原文地址:https://www.cnblogs.com/jcf94/p/3959826.html
Copyright © 2011-2022 走看看