优先级队列

来源:互联网 发布:软件服务外包合同范本 编辑:程序博客网 时间:2024/04/30 12:58

优先级的基本概念:

优先队列是0个或多个元素的集合,每个元素都有一个优先权或值,对优先队列执行的操作有1) 查找;2) 插入一个新元素;3) 删除.在最小优先队列(min priorityqueue)中,查找操作用来搜索优先权最小的元素,删除操作用来删除该元素;对于最大优先队列(max priority queue),查找操作用来搜索优先权最大的元素,删除操作用来删除该元素.优先权队列中的元素可以有相同的优先权,查找与删除操作可根据任意优先权进行.

又上面的优先级队列的介绍,我们可以想到我们学习过的大小堆,大堆表示最高优先级队列,小堆表示最低优先级队列,没错,我们的优先级队列就是有堆实现

下面是库提供的优先级队列的调用方法,我们可以直接使用
这里写图片描述

接下来介绍优先级队列的自己实现

  • 首先我们创建一个堆,见上篇博客

  • 然后实现优先级队列的基本操作

#include<stdio.h>#include"heap.cpp"//包含自己创建的堆#include<iostream>using namespace std;template<class T>class PriorityQueue{public:    PriorityQueue()    {}    void push(const T& value)    {        _heap.Insert(value);    }    void Pop()    {        _heap.Remove();    }    const T& Top()const    {        return _heap.Top();    }    bool Empty()const    {        return _heap.Empty();    }    size_t Size()const    {        return _heap.Size();    }private:    heap<T> _heap;};void funtest(){    PriorityQueue<int> q;    q.push(1);    q.push(2);    q.push(3);    q.Pop();    bool ret = q.Empty();    int ret1 = q.Size();    int ret2 = q.Top();}int main(){    funtest();    getchar();    return 0;}
0 0
原创粉丝点击