c语言中优先级队列_C ++中的优先级队列

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.

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

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

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

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

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

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 
#include 

std::priority_queue pq1;
std::priority_queue pq2;
std::priority_queue 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 empty

    empty()->检查优先级队列是否为空
  • size() -> Returns the number of elements in the Queue

    size()->返回队列中的元素数
  • top() -> Returns the element at the top of the Queue

    top()->返回队列顶部的元素
  • push() -> Pushes an element to the bottom of the Queue

    push()->将元素推到队列底部
  • pop() -> Pops the last element from the Queue

    pop()->从队列中弹出最后一个元素

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

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


#include 
#include 
#include 

using namespace std;

void print_pqueue (priority_queue pq) {
    // Prints the Priority Queue
    priority_queue 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 integers
    priority_queue 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:

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

c语言中优先级队列_C ++中的优先级队列_第1张图片
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 : 400

Priority 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, CompareClass()> pqueue;

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

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

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

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


#include 
#include 
#include 

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, CompareClass> pq) {
    // Prints the Priority Queue
    priority_queue, 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 integers
    priority_queue, 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 : 50

Priority 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 ++中的优先级队列)