温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c++中如何使用优先队列

发布时间:2021-07-12 10:02:30 来源:亿速云 阅读:122 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关c++中如何使用优先队列,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。

首先要包含头文件#include<queue>, 他和queue不同的就在于我们可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队。

优先队列具有队列的所有特性,包括队列的基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的。

和队列基本操作相同:

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

定义:priority_queue<Type, Container, Functional>Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式。

当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。一般是:

//升序队列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 00 1 2 3 4cbd abcd abc请按任意键继续. . .

2、用pair做优先队列元素的例子:

规则: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 51 31 2请按任意键继续. . .

3、用自定义类型做优先队列元素的例子

#include <iostream>#include <queue>using namespace std;//方法1struct tmp1 //运算符重载<{  int x;  tmp1(int a) {x = a;}  bool operator<(const tmp1& a) const  {    return x < a.x; //大顶堆  }};//方法2struct tmp2 //重写仿函数{  bool operator() (tmp1 a, tmp1 b)   {    return a.x < b.x; //大顶堆  }};int main() {  tmp1 a(1);  tmp1 b(2);  tmp1 c(3);  priority_queue<tmp1> d;  d.push(b);  d.push(c);  d.push(a);  while (!d.empty())   {    cout << d.top().x << '\n';    d.pop();  }  cout << endl;  priority_queue<tmp1, vector<tmp1>, tmp2> f;  f.push(b);  f.push(c);  f.push(a);  while (!f.empty())   {    cout << f.top().x << '\n';    f.pop();  }}

运行结果:

321321请按任意键继续. . .

上述就是小编为大家分享的c++中如何使用优先队列了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI