Home >Backend Development >C++ >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:
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>
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
<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!