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

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

DDD
DDDOriginal
2024-10-25 05:28:02591browse

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

Declaring a Priority Queue in C with Custom Comparators

When working with custom comparators in C , declaring a priority queue can present challenges. Let's delve into your specific issue and explore the correct approach.

As mentioned in the provided code snippet, you are using bool Compare(Node a, Node b) as the comparator function, which exists outside the Node class. To rectify the issue, consider the following:

  1. Define a Compare Class: Instead of using a function pointer, you can define a class with an overloaded operator() implementation. For example:

    <code class="cpp">class Compare {
    public:
        bool operator()(const Node& a, const Node& b) {
            // Your comparison logic here
        }
    };</code>
  2. Declare the Priority Queue: Once you have defined the Compare class, declare the priority queue using the following syntax:

    <code class="cpp">priority_queue<Node, vector<Node>, Compare> openSet;</code>

Alternatively, if you cannot define a custom class due to limitations, you can use std::function as the comparator type. However, it may not be as efficient as the first approach.

<code class="cpp">bool Compare(const Node& a, const Node& b) {
    // Your comparison logic here
}

int main() {
    std::priority_queue<Node, vector<Node>, std::function<bool(const Node&, const Node&)>> openSet(Compare);
    return 0;
}</code>

By adhering to one of these approaches, you can effectively declare a priority queue using a custom comparator in C .

The above is the detailed content of How to Declare a Priority Queue with Custom Comparators 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