为什么当我尝试将priority_queue与参数一起使用作为指向结构的指针时会弹出错误
Why is an error popping out when i am trying to use priority_queue with parameters as pointer to a structure
>## 优先级队列会抛出指针错误。当我尝试使用结构指针作为优先级队列的参数并使用比较器函数时,代码给出了错误,但优先级似乎适用于对象。##
#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.
}
你的代码有 3 个问题:
1(在C++17中存在一个std::d ata,但是您在struct data
声明之前增加了using namespace std;
struct data
。 这可能会导致命名冲突。
2(函数调用运算符是operator()
,而不是operate
。
3(您正在使用可怕的#include <bits/stdc++.h>
,这不仅是非标准的,还会导致与上述第1项相关的各种问题。
以下是解决上述所有这些问题的代码:
#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));
}
现场示例
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- C++:映射结构中的结构指针
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 类的静态结构指针声明在C++
- 在两个.cpp文件之间定义全局类/结构指针
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何在地图中使用结构指针
- 结构指针在"新"调用上给出已分配的地址?
- 铸造结构指针指向C 的工会指针
- c++ 结构指针在初始化为 NULL 时无法读取内存
- 函数中的结构指针的地址为0x1
- C 用结构指针初始化结构
- C 结构指针铸成数组Interop C#
- 方法中不允许访问结构指针
- 如何打印出结构指针
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 尝试将结构指针传递给类时出错
- 初始化结构指针的值
- 使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?