priority_queue 的简单使用方法

优先队列(priority queue)
普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。
在优先队列中,元素被赋予优先级(优先级可自己定义)。
当访问元素时,具有最高优先级的元素最先删除。
优先队列具有最高进先出 (largest-in,first-out)的行为特征。

在使用的时候 一定要有  <queue>的头文件。。。据学长介绍,STL里的东西 会用就行, 不要太深入理解。

今天刚学STL,小总结一下 优先队列的东西。。



#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;

///q.push (x);///将x接到队列的末端。
///q.top ();///访问队首元素
///q.pop ();///删除队首元素
///q.front();///访问队首元素   最早被压入队列的元素。
///q.back();///访问队尾元素    最后被压入队列的元素。
///q.size();///访问队列中的元素个数
///q.empty ();///判断是否为空   当队列空时,返回true。

struct cmp
{
    bool operator () (int &a,int &b)
    {
        return a > b;///从小到大  如果想要从大到小 改成 '<'
    }
};

struct node
{
    int x;
    bool operator < (const node &a) const
    {
        return a.x < x;///从小到大  如果想要从大到小 改成 '>'
    }
}p;

int main()
{
    int n,x;
    ///priority_queue <int>q;///默认从大到小排序输出
    ///priority_queue <int ,vector<int> , greater <int>  >q;///从小到大排序输出  >>会被认为是错误  中间要加空格
    ///priority_queue <int,vector<int> ,less <int >  >q;///从大到小
    ///priority_queue <int ,vector <int>, cmp>q;
    priority_queue <node>q;
    while (~scanf ("%d",&n))
    {
        while (!q.empty ())///使用的时候要先判断队列是否为空 不为空的话就清空。。
            q.pop ();
        for (int i = 0; i < n; i++)
        {
///           scanf ("%d",&x);
///           q.push (x);
            scanf ("%d",&p.x);
            q.push (p);
        }
        while (!q.empty ())
        {
            //int s = q.top ();
            struct node  s = q.top ();
            printf ("%d  ",s.x);
            q.pop ();
        }
        printf ("\n");

    }
    return 0;
}



参考博客:http://blog.chinaunix.net/uid-21712186-id-1818266.html

http://blog.csdn.net/u013476556/article/details/38372311









  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值