Home > Backend Development > C++ > body text

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

DDD
Release: 2024-10-25 05:28:02
Original
590 people have browsed it

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>
    Copy after login
  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>
    Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!