当我尝试使用带有参数的priority_queue作为结构指针时,为什么会弹出错误 [英] Why is an error popping out when i am trying to use priority_queue with parameters as pointer to a structure

查看:44
本文介绍了当我尝试使用带有参数的priority_queue作为结构指针时,为什么会弹出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

##优先级队列使用指针引发错误.当我尝试将结构指针用作优先级队列的参数并使用比较器功能时,代码给出了错误,但优先级似乎可以很好地与对象配合使用.##

 #include< bits/stdc ++.h>使用命名空间std;结构数据{诠释成本;int节点;int k;data(int a,int b,int c):cost(a),node(b),k(c){};};结构cmp{布尔操作(数据* p1,数据* p2){返回p1-> cost< p2->成本;}};int main(){priority_queue< data *,向量< data *>,cmp>pq;pq.push(新数据(0,2,3));//此行将引发错误说明(从此处开始要求),并且在要求之前未写入任何内容.} 

解决方案

您的代码有3处错误:

1)C ++中存在一个 std :: data 17,但是您有一个 struct数据,在声明 struct数据之前,加上了 using命名空间std; .这可能会导致命名冲突.

2)函数调用运算符是 operator(),而不是 operate .

3)您正在使用可怕的 #include< bits/stdc ++.h> ,这不仅是非标准的,还会引起与上述项目1)有关的各种问题./p>

这是您的代码,可以解决上述所有这些问题:

  #include< vector>#include< queue>结构数据{诠释成本;int节点;int k;data(int a,int b,int c):cost(a),node(b),k(c){};};结构cmp{bool运算符()(数据* p1,数据* p2){返回p1-> cost<p2->成本;}};int main(){std :: priority_queue< data *,std :: vector< data *>,cmp>pq;pq.push(新数据(0,2,3));} 

实时示例

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

 }

解决方案

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

这篇关于当我尝试使用带有参数的priority_queue作为结构指针时,为什么会弹出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆