当前位置: 移动技术网 > 移动技术>移动开发>Android > 优先队列基本用法

优先队列基本用法

2020年07月27日  | 移动技术网移动技术  | 我要评论

priority_queue在头文件#include中,他能自定义优先级,优先级高的先出队,基本操作和queue差不多,就是priority_queue自带排序,排序可自定义

top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容

定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。
不多说,基本就下面代码的手法,其他的我也不会(我太菜了)

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <ctype.h>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0)
#define mcy(a,b) memcpy(a,b,sizeof(a))
priority_queue<int,vector<int>,greater<int> >a;//升序排列
priority_queue<int,vector<int>,less<int> >b;//降序排列
priority_queue<string,vector<string>,greater<string> >c;
priority_queue<string,vector<string>,less<string> >d;
struct node {
    int x;
}aa[1005];
struct cmp
{
    bool operator() (node m,node n)
    {
        return m.x<n.x;
    }
};
int main()
{
    for(int i=1;i<=9;++i)
    {
        a.push(i);
        b.push(i);
    }
    while (!a.empty())
    {
        cout << a.top() << ' ';
        a.pop();
    }
    cout << endl;
    while (!b.empty())
    {
        cout << b.top() << ' ';
        b.pop();
    }
    cout << endl;
    string x,y,z;
    x="aaab";
    y="aabc";
    z="abc";
    c.push(x),c.push(y),c.push(z);
    d.push(x),d.push(y),d.push(z);
    while (!c.empty())
    {
        cout << c.top() << ' ';
        c.pop();
    }
    cout << endl;
    while (!d.empty())
    {
        cout << d.top() << ' ';
        d.pop();
    }
    cout << endl;
    //结构体类型
    priority_queue<node,vector<node>,cmp>ss;
    for(int i=1;i<=5;++i)
    {
        aa[i].x=rand();
        ss.push(aa[i]);
    }
    while (!ss.empty())
    {
        cout << ss.top().x << ' ';
        ss.pop();
    }
    cout << endl;
}
输出:
1 2 3 4 5 6 7 8 9 
9 8 7 6 5 4 3 2 1 
aaab aabc abc 
abc aabc aaab 
1622650073 1144108930 984943658 282475249 16807 

本文地址:https://blog.csdn.net/bug_and_dbug/article/details/107589773

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网