Home  >  Article  >  Backend Development  >  How to Declare a Priority Queue with a Custom Comparator in C ?

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

DDD
DDDOriginal
2024-10-24 13:31:02257browse

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>

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>

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!

Statement:
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