C++中优先队列的使用

匿名 (未验证) 提交于 2019-12-03 00:40:02

既然是队列那么先要包含头文件#include <queue>

优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的 。
定义:priority_queue<Type, Container, Functional>
TypeContainerFunctional

//升序队列 priority_queue <int,vector<int>,greater<int> > q; //降序队列 priority_queue <int,vector<int>,less<int> >q;  //greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)

1.基本类型例子:

#include<iostream> #include <queue> using namespace std; int main()  {     //对于基础类型 默认是大顶堆     priority_queue<int> a;      //等同于 priority_queue<int, vector<int>, less<int> > a;      //             这里一定要有空格,不然成了右移运算符↓     priority_queue<int, vector<int>, greater<int> > c;  //这样就是小顶堆     priority_queue<string> b;      for (int i = 0; i < 5; i++)      {         a.push(i);         c.push(i);     }     while (!a.empty())      {         cout << a.top() <<  ;         a.pop();     }      cout << endl;      while (!c.empty())      {         cout << c.top() <<  ;         c.pop();     }     cout << endl;      b.push("abc");     b.push("abcd");     b.push("cbd");     while (!b.empty())      {         cout << b.top() <<  ;         b.pop();     }      cout << endl;     return 0; }

输出:

4 3 2 1 0 0 1 2 3 4 cbd abcd abc

2.pair的比较,先比较第一个元素,第一个相等比较第二个

#include <iostream> #include <queue> #include <vector> using namespace std; int main()  {     priority_queue<pair<int, int> > a;     pair<int, int> b(1, 2);     pair<int, int> c(1, 3);     pair<int, int> d(2, 5);     a.push(d);     a.push(c);     a.push(b);     while (!a.empty())      {         cout << a.top().first <<   << a.top().second << \n;         a.pop();     } }

输出:

2 5 1 3 1 2

3.对于自定义类型

#include <iostream> #include <queue> using namespace std;  //方法1 struct tmp1 //运算符重载< {     int x;     tmp1(int a) {x = a;}     
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!