初始化并插入优先级队列 (C++)

Initializing and Inserting into a Priority Queue (C++)

本文关键字:C++ 队列 优先级 插入 初始化      更新时间:2023-10-16

我以前从未使用过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)时,该元素会自动放置在正确的位置吗?

是的。

希望这有帮助,不要混淆!