初始化并插入优先级队列 (C++)
Initializing and Inserting into a Priority Queue (C++)
我以前从未使用过STL C++优先级队列,我发现网站上的详细信息有点令人困惑。
我想创建一个节点的优先级队列,我将其定义为:
struct Node {
string data;
int weight;
Node *left, *right;
}
我还根据节点的权重按升序插入队列。但是,我不知道最终PQ中会有多少个节点。
我对使用哪个构造函数来创建 PQ 感到困惑。目前,我有:
std::priority_queue<Node> myQueue;
但是由于我希望队列根据节点的权重进行排序,我应该使用构造函数吗:
priority_queue (const Compare& comp, const Container& ctnr);
这样行得通吗?在这种情况下,CTNR 会"节点"吗?
最后,当我想将元素推送到priority_queue(使用 STL priority_queue::p ush)时,该元素会自动放置在正确的位置吗?
谢谢。
初始化不会确定优先级队列的运行方式。如果您希望它以特定方式排序,则有两种选择。
第一个选项是在Node
对象上定义 <
运算符,以便按照所需的方式比较它们。
struct Node {
string data;
int weight;
Node *left, *right;
bool operator<(const Node& n) const {
return weight < n.weight;
// or "weight > n.weight" if you want the smallest weight at the top
}
};
std::priority_queue<Node> myQueue;
第二个选项是定义自定义比较器类型并将其指定为模板参数:
struct NodeComp {
bool operator()(const Node& n1, const Node& n2) const {
return n1.weight < n2.weight;
// or "n1.weight > n2.weight" if you want the smallest weight at the top
}
};
std::priority_queue<Node, std::vector<Node>, NodeComp> myQueue;
您可以使用:
struct cmp
{
bool operator() (Node const &a, Node &b) { return a.weight < b.weight; }
};
typedef std::priority_queue<Node, std::vector<Node>,cmp> My_queue;
当我想将元素推入priority_queue(使用 STL priority_queue::p ush)时,该元素会自动放置在正确的位置吗?
是的。
希望这有帮助,不要混淆!
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Android NDK传感器向事件队列报告奇怪的间隔
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在一个读写器队列中,我可以用volatile替换原子吗
- 为什么我的多线程作业队列崩溃
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 使用"Task"函数指针队列定义作业管理器
- 在c++队列中使用pop和visit实现线程安全
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 打印优先级队列
- 共享队列的线程安全
- 带自定义比较器的最小优先级队列
- 在 Vulkan Qt 中获取队列系列
- 堆栈和队列是否像C++中的数组一样传递?
- 在C++中创建队列 - 什么是 malloc 错误?
- 优先级队列自定义比较器