Home > Backend Development > C++ > body text

How to Declare a Priority Queue with a Custom Comparator in C ?

DDD
Release: 2024-10-24 13:31:02
Original
343 people have browsed it

How to Declare a Priority Queue with a Custom Comparator in C  ?

Declaring a Priority Queue with a Custom Comparator in C

In C , when attempting to declare a priority queue that utilizes a custom comparator, it is essential to define the comparator correctly. The error "Compare" is not a type name arises when the comparator is not declared as a class or a standalone function.

To resolve this, you can define a class for the comparator and overload the operator() for it, as demonstrated in the following example:

<code class="cpp">class Compare
{
public:
    bool operator() (Node a, Node b)
    {
        // Comparator logic
    }
};</code>
Copy after login

Alternatively, you can utilize a std::function to define the comparator, as shown below:

<code class="cpp">bool Compare(Node a, Node b)
{
    // Comparator logic
}

std::priority_queue<Node, std::vector<Node>, std::function<bool(Node, Node)>> pq(Compare);</code>
Copy after login

By following these approaches, you can effectively declare a priority queue with a custom comparator in C .

The above is the detailed content of How to Declare a Priority Queue with a Custom Comparator in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template