问题
## Priority Queue throws an error with pointers. When I try to use structure pointers as parameter for priority queue and use comparator function the code gives an error , but priority seems to work fine with objects. ##
#include<bits/stdc++.h>
using namespace std;
struct data
{
int cost;
int node;
int k;
data(int a,int b,int c):cost(a),node(b),k(c){};
};
struct cmp
{
bool operate(data *p1,data *p2)
{
return p1->cost<p2->cost;
}
};
int main ()
{
priority_queue<data*,vector<data*>,cmp> pq;
pq.push(new data(0,2,3)); //This line throws an error stating ( required from here) and there is nothing written before required.
}
回答1:
There are 3 things wrong with your code:
1) There is a std::data that exists in C++ 17, yet you have a struct data
with the addition of using namespace std;
before the declaration of struct data
. This could cause a naming clash.
2) The function call operator is operator()
, not operate
.
3) You're using the dreaded #include <bits/stdc++.h>
, which not only is non-standard, causes all sorts of issues pertaining to item 1) above.
Here is your code that addresses all of these issues above:
#include <vector>
#include <queue>
struct data
{
int cost;
int node;
int k;
data(int a,int b,int c):cost(a),node(b),k(c){};
};
struct cmp
{
bool operator()(data *p1,data *p2)
{
return p1->cost < p2->cost;
}
};
int main ()
{
std::priority_queue<data*, std::vector<data*>,cmp> pq;
pq.push(new data(0,2,3));
}
Live Example
来源:https://stackoverflow.com/questions/58423310/why-is-an-error-popping-out-when-i-am-trying-to-use-priority-queue-with-paramete