c语言中优先级队列

A Priority Queue is a variant of a Queue such that it’s elements are ordered based on their priority. C++ has a built-in priority queue data structure in it’s Standard Template Library (STL).

优先级队列队列的一种变体,可以根据其优先级对元素进行排序。 C ++在其标准模板库( STL )中具有内置的优先级队列数据结构。

Priority queues are implemented as container adapters in C++.

优先级队列在C ++中作为容器适配器实现。

This means that like other container adapters, they have member functions for the container objects.

这意味着像其他容器适配器一样,它们具有容器对象的成员功能。

Let’s understand how we can use the Priority Queue container in C++ to make our own priority queues.

让我们了解如何使用C ++中的Priority Queue容器创建自己的优先级队列。



创建一个优先队列 (Create a Priority Queue)

We can create a priority queue by declaring a priority queue variable of the type std::priority_queue<type>.

我们可以通过声明类型为std::priority_queue<type>的优先级队列变量来创建优先级队列。

The std:: namespace signifies that this supports STL (Standard Template Library) operations.

std::名称空间表示它支持STL (标准模板库)操作。

NOTE: To use this, we must include the <queue> header file in our program.

注意 :要使用此功能,我们必须在程序中包含<queue>头文件。

Since this is a container of the STL, we must provide the template type for the queue. It could be anything from int, float, char, string, etc.

由于这是STL的容器,因此我们必须提供队列的模板类型。 它可以是intfloatcharstring等任何东西。

For example, the following are valid declarations of a priority queue.

例如,以下是优先级队列的有效声明。


#include <queue>
#include <string>std::priority_queue<int> pq1;
std::priority_queue<float> pq2;
std::priority_queue<std::string> pq3;

优先级队列上的常用方法 (Common Methods on a Priority Queue)

Some of the methods which the priority queue container supports are namely:

优先级队列容器支持的一些方法是:

  • empty() -> Checks if the Priority Queue is emptyempty()->检查优先级队列是否为空
  • size() -> Returns the number of elements in the Queuesize()->返回队列中的元素数
  • top() -> Returns the element at the top of the Queuetop()->返回队列顶部的元素
  • push() -> Pushes an element to the bottom of the Queuepush()->将元素推到队列底部
  • pop() -> Pops the last element from the Queuepop()->从队列中弹出最后一个元素

Let’s understand the above methods using an example. The below code uses all the above methods involving the priority queue.

让我们通过一个例子来了解上述方法。 下面的代码使用上述所有涉及优先级队列的方法。


#include <iostream>
#include <string>
#include <queue>using namespace std;void print_pqueue (priority_queue<int> pq) {// Prints the Priority Queuepriority_queue<int> copy_q = pq;cout << "Priority Queue : ";while (!copy_q.empty()) {cout << copy_q.top() << " ";copy_q.pop();}cout << "\n";
}int main() {// Program demonstrating use of Priority Queue// methods// Create an empty priority queue of integerspriority_queue<int> queue_int;// Is the Queue empty now? Yes!cout << "Is the Queue empty now? : " << (queue_int.empty() ? "Yes" : "No") << endl;// Let's add some elements!cout << "Adding some elements...\n";queue_int.push(100);queue_int.push(200);queue_int.push(400);queue_int.push(50);cout << "Number of elements : " << queue_int.size() << endl;cout << "Top element : " << queue_int.top() << endl << endl;print_pqueue(queue_int);cout << "Popping element from the top...\n\n";queue_int.pop();print_pqueue(queue_int);return 0;
}

Here, we create a priority queue of integers and insert the elements 100, 200, 400 and 50 in order.

在这里,我们创建一个整数优先级队列,并依次插入元素100、200、400和50。

Note that since a priority queue has the elements sorted in descending order from the top, the insertion will look like this:

请注意,由于优先级队列的元素从顶部开始按降序排列,因此插入将如下所示:

Priority Queue
优先队列

After pushing to the queue, we pop the topmost element from the Queue, i.e, the element with the highest priority.

推送到队列后,我们从队列中弹出最上面的元素,即具有最高优先级的元素。

Therefore, 400 will be popped out, making 200 as the new head of the Queue.

因此,将弹出400 ,使200作为队列的新头。


Is the Queue empty now? : Yes
Adding some elements...
Number of elements : 4
Top element : 400Priority Queue : 400 200 100 50
Popping element from the top...Priority Queue : 200 100 50

This shows how we can use the priority queue container easily. Let us move on to a case where you want to have your own priority scheme.

这显示了我们如何轻松使用优先级队列容器。 让我们继续讨论您想要拥有自己的优先级方案的情况。



实现我们自己的比较功能 (Implementing our own Comparison function)

By default, the C++ priority queue evaluates priority only based on sorted values. We can change this, by implementing our own comparison function!

默认情况下,C ++优先级队列仅根据排序后的值评估优先级。 我们可以通过实现自己的比较功能来改变它!

We can overload the default comparison function, by overloading the STL comparison operator.

我们可以通过重载STL 比较运算符来重载默认比较功能。

For this, we must create a comparison class first. Let us call it CompareClass and then introduce our custom comparison in the operator() block.

为此,我们必须首先创建一个比较类。 让我们将其CompareClass ,然后在operator()块中引入我们的自定义比较。

This must return a bool, since this is a comparison function, and must also be public.

由于这是一个比较函数,因此必须返回bool ,并且还必须是public

The code structure will look similar to this. We are now comparing based on the ascending order of values!

代码结构看起来与此类似。 我们现在基于值的升序进行比较!


// Create a Comparison Class for our
// integer priority queue
class CompareClass {public:bool operator() (int a, int b) {if (a > b)return true;return false;}
};

We are still not yet done. We need to make the compiler realize that we are using this new class for our comparison operator.

我们还没有完成。 我们需要使编译器意识到我们将这个新类用于比较运算符。

For that, we will need to add two more parameters to our priority_queue<> STL invocation.

为此,我们将需要在我们的priority_queue<> STL调用中添加两个以上的参数。


priority_queue<type, vector<type>, CompareClass()> pqueue;

The second parameter tells the compiler that the queue is implemented as a vector<type>. The third one is our Comparison Class.

第二个参数告诉编译器该队列被实现为vector<type> 。 第三个是我们的比较类。

We will modify our old code to include these new changes.

我们将修改旧代码以包括这些新更改。


#include <iostream>
#include <string>
#include <queue>using namespace std;// Create a Comparison Class for our
// integer priority queue
class CompareClass {public:bool operator() (int a, int b) {if (a > b)return true;return false;}
};void print_pqueue (priority_queue<int, vector<int>, CompareClass> pq) {// Prints the Priority Queuepriority_queue<int, vector<int>, CompareClass> copy_q = pq;cout << "Priority Queue : ";while (!copy_q.empty()) {cout << copy_q.top() << " ";copy_q.pop();}cout << "\n";
}int main() {// Program demonstrating use of Priority Queue// methods// Create an empty priority queue of integerspriority_queue<int, vector<int>, CompareClass> queue_int;// Is the Queue empty now? Yes!cout << "Is the Queue empty now? : " << (queue_int.empty() ? "Yes" : "No") << endl;// Let's add some elements!cout << "Adding some elements...\n";queue_int.push(100);queue_int.push(200);queue_int.push(400);queue_int.push(50);cout << "Number of elements : " << queue_int.size() << endl;cout << "Top element : " << queue_int.top() << endl << endl;print_pqueue(queue_int);cout << "Popping element from the top...\n\n";queue_int.pop();print_pqueue(queue_int);return 0;
}

Output

输出量


Is the Queue empty now? : Yes
Adding some elements...
Number of elements : 4
Top element : 50Priority Queue : 50 100 200 400
Popping element from the top...Priority Queue : 100 200 400

Observe that we insert elements based on their increasing order of values now, so the top of the queue is the lowest element.

观察到我们现在根据其值的升序插入元素,因此队列的顶部是最低的元素。

Thus, we have successfully implemented our own comparison function!

因此,我们已经成功实现了自己的比较功能!



结论 (Conclusion)

In this article, we looked at the C++ Priority Queue container. We also saw some of the methods involved in manipulating them.

在本文中,我们研究了C ++ Priority Queue容器。 我们还看到了一些操纵它们的方法。

Recommended Read: Hash Tables in C++

推荐阅读: C ++中的哈希表



参考资料 (References)

  • cplusplus.com page on Priority Queues有关优先级队列的cplusplus.com页面


翻译自: https://www.journaldev.com/35189/priority-queue-in-c-plus-plus

c语言中优先级队列

c语言中优先级队列_C ++中的优先级队列相关推荐

  1. c#中如何删除数组中的元素_C中的数组

    c#中如何删除数组中的元素 为什么我们需要数组? (Why do we need Arrays?) Consider the problem of storing 10 integers. The n ...

  2. c++中的模板_C ++中的模板

    c++中的模板 Templates in C++ are an abstract version of Generic Programming wherein the code is written ...

  3. c语言面向对象编程中的类_C ++中的面向对象编程

    c语言面向对象编程中的类 Object oriented programming, OOP for short, aims to implement real world entities like ...

  4. c 语言bool 类型数据_C ++中的bool数据类型

    c 语言bool 类型数据 In C++ programming language, to deal with the Boolean values – C++ added the feature o ...

  5. c++中的队列_C ++中的队列

    c++中的队列 介绍 (Introduction) We worked on the working as well as the implementation of a Stack in C++ i ...

  6. C语言面向对象编程的类是指,c语言面向对象编程中的类_C ++中的面向对象编程...

    c语言面向对象编程中的类 Object Oriented programming is a programming style that is associated with the concept ...

  7. python中双冒号_c++中冒号(:)和双冒号(::)的用法和c/c++ 位域结构体

    1.冒号(:)用法 (1)表示结构体内 位域的定义(即该变量占几个bit空间) typedef struct _XXX{ unsigned char a:4; unsigned char c; }XX ...

  8. c++中的向量_C ++中的向量

    c++中的向量 A Vectors in C++ is an array-like container that can change dynamically in size. Being a par ...

  9. for循环在c++中的用法_C ++中的循环

    for循环在c++中的用法 Loops come into picture when we need to execute a particular action in a repeated mann ...

最新文章

  1. 单片机从事什么工作?只会51单片机能找到工作吗?
  2. Android 应用防止被二次打包指南
  3. 如何用纯 CSS 创作一个方块旋转动画
  4. 唐诗三百首加密软件如何使用_视频加密一机一码软件该如何选择?有哪些因素影响?...
  5. IT项目管理总结:第一章 项目管理概述
  6. RabbitMQ惰性队列
  7. LiveVideoStackCon讲师热身分享 ( 二 ) —— 中美互动直播比较
  8. [2020.11.26NOIP模拟赛]勇者的后缀【SA,RMQ,主席树,二分】
  9. 转 【MQTT】在Windows下搭建MQTT服务器
  10. DB2 CASE/IF 条件控制语句
  11. dll = MinGW gcc 生成动态链接库 dll 的一些问题汇总
  12. C++ 限定名称查找
  13. 最大似然估计、MAP及贝叶斯估计
  14. 阿里大淘系模型治理阶段性分享
  15. SPSS输出结果统计表与统计图的专业性编辑及三线表定制格式
  16. mysql 导入dmp_navicat怎么导入dmp文件
  17. 从我做起 - 抵制1024程序员节-不要再自黑了
  18. 计算机怎么按根号三的四次方,如何在excel中设置开4次方根号公式 | excle根号3公式...
  19. java集合入门和深入学习,看这篇就差不多了
  20. 【数理统计】调和平均值

热门文章

  1. T1155 金明的预算方案 codevs
  2. if __name__ == __main__如何正确理解
  3. 【转】各种字符串算法大总结
  4. Asp.net中Global.asax
  5. 新随笔 注:关注后可阅读(持续更新--------)
  6. plsql本机不安装数据库连接远程数据库
  7. 【pwnable.kr】passcode
  8. linux shell 递归统计代码行数
  9. 公司有内部推荐的名额
  10. 【OpenCV】IplImage和char *的相互转换,以及极易忽视的细节