C++ Priority Queue 优先队列简要使用

C++ Priority Queue 优先队列简要使用

优先队列与普通队列的区别
优先队列:排序按照预定的优先级进行排序
普通队列:按照插入的顺序进行排序


#include <iostream>
#include <queue>
#include <vector>
#include <time.h>
#include <random>
#include<functional>
using namespace std;

struct compare_fun
{
    bool operator() (int &a, int &b) {
        return a < b;
    }

};


struct Task
{
    int id; //任务id
    int prid; //优先级序号
    float value;//附加值

    bool operator < (const Task &a) const {
        return prid > a.prid;//最小值优先
    }

};


/****************************************!
*@author elegant
*@date   2018年7月17日
*@param[out] 
****************************************/

vector<Task> init_task_queue;
priority_queue <Task> taskque;

void init_task()
{
    Task tmp;
    //srand((int)time(0)); 当前时间为随机数种子
    srand(5); //随机数种子
    for (size_t i = 0; i < 8; i++)
    {
        tmp.id = i;
        tmp.prid = rand() % 100;
        tmp.value = (i+1)*1.101;
        init_task_queue.push_back(tmp);
        taskque.push(tmp);
    }

}



int main(int argc,char *argv[])
{
    priority_queue <int,vector<int>, compare_fun> qp;



    qp.push(1);
    qp.push(3);
    qp.push(90);
    qp.push(2);
    qp.push(13);
    qp.push(76);
    qp.push(30);
//默认优先队列
    cout << "test priority  queue" << endl;
    while (!qp.empty())
    {
        cout << " " << qp.top();
        qp.pop();

    }

    cout << " \r\n" << endl;
//初始化队列
    init_task();
//输出原始队列的排序
    cout << " init queue" << endl;
    cout << "   id   priority   value" << endl;
    while (!init_task_queue.empty())
    {
        cout << "   " << init_task_queue.begin()->id <<"    "<< init_task_queue.begin()->prid << "          " << init_task_queue.begin()->value << endl;
        init_task_queue.erase(init_task_queue.begin());

    }

    cout << " \r\n" << endl;
    cout << " task queue" << endl;
    cout << "   id   priority     value" << endl;
    //输出按照Task优先级排序的优先队列
    while (!taskque.empty())
    {
        cout << "--- " << taskque.top().id << "       " << taskque.top().prid << "       " << taskque.top().value <<endl;
        taskque.pop();

    }

    cout << " \r\n" << endl;
    system("pause");

}

这里写图片描述

如上图所示:
优先队列按照优先级序列小的部分进行排序,而与队列数据插入的顺序无关

猜你喜欢

转载自blog.csdn.net/starelegant/article/details/81085209