简体   繁体   English

当我尝试使用带有参数的priority_queue作为指向结构的指针时,为什么会弹出错误

[英]Why is an error popping out when i am trying to use priority_queue with parameters as pointer to a structure

## Priority Queue throws an error with pointers. ## Priority Queue 使用指针引发错误。 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.当我尝试使用结构指针作为优先级队列的参数并使用比较器 function 时,代码会出现错误,但优先级似乎适用于对象。 ## ##

 #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.

 }

There are 3 things wrong with your code:您的代码有 3 个问题:

1) There is a std::data that exists in C++ 17, yet you have a struct data with the addition of using namespace std; 1) C++ 17 中存在一个std::data ,但是您有一个struct data ,并添加了using namespace std; before the declaration of struct data .在声明struct data之前。 This could cause a naming clash.这可能会导致命名冲突。

2) The function call operator is operator() , not operate . 2) function 调用operate符是operator() ,不是 operation 。

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. 3) 您正在使用可怕的#include <bits/stdc++.h> ,这不仅是非标准的,还会导致与上述第 1) 项有关的各种问题。

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现场示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM