std :: Priority_queue包含fuctor的结构
std::priority_queue contain struct with functor
我想使用函数将 HeapNode
添加到 std::priority_queue
中。
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct HeapNode
{
bool operator()(const struct HeapNode &a,const struct HeapNode &b) const
{
return b.c>=a.c;
}
double c;
double v;
}h;
int main()
{
priority_queue<struct HeapNode,vector<struct HeapNode>,h> H;
struct HeapNode a={1,2};
struct HeapNode b={3,2};
struct HeapNode c={6,2};
H.push(a);
H.push(b);
H.push(c);
}
但是有错误:
queue.cpp: In function ‘int main()’:
queue.cpp:19:65: error: type/value mismatch at argument 3 in template parameter list for ‘template<class _Tp, class _Sequence, class _Compare> class std::priority_queue’
priority_queue<struct HeapNode,vector<struct HeapNode>,heapnode> H;
^
queue.cpp:19:65: note: expected a type, got ‘heapnode’
queue.cpp:23:4: error: request for member ‘push’ in ‘H’, which is of non-class type ‘int’
H.push(1);
^
queue.cpp:24:4: error: request for member ‘push’ in ‘H’, which is of non-class type ‘int’
H.push(2);
^
queue.cpp:25:4: error: request for member ‘push’ in ‘H’, which is of non-class type ‘int’
H.push(3);
^
我已经研究了参考,但我仍然对std::priority_queue
。
h
指定具有静态存储持续时间的对象。Priority_queue模板期望类型。错误对此很清楚:
error: type/value mismatch at argument 3 in template parameter list
现在,您使用类型本身作为函子来比较它有点奇怪(效率低下((1(。我建议将其分开:
struct HeapNode
{
double c;
double v;
};
struct HeapNodeCompare
{
bool operator()(const struct HeapNode &a,const struct HeapNode &b) const
{
return b.c>=a.c;
}
};
现在可以简单地定义您的队列:
priority_queue<HeapNode, vector<HeapNode>, HeapNodeCompare> H;
(1(我说效率低下,因为必须构建函数才能使用才能使用。您的类型具有有意义的状态,可以占据存储。如果您将类型本身用作函子,那有点浪费。单独的类型没有状态,将占据最小存储。
您对priority_queue
模板实例化的第三个参数是全局变量,而不是类型。您声明了struct HeapNode
,然后声明为struct HeapNode
类型的全局变量h
。在模板实例化中,由struct HeapNode
替换h
。
另外,我认为最好有一个单独的比较器类,而不是重复您的节点类。这是因为priority_queue
将创建struct HeapNode
的实例以具有比较器。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- std :: Priority_queue包含fuctor的结构