【问题标题】:Initializing and Inserting into a Priority Queue (C++)初始化并插入优先级队列 (C++)
【发布时间】:2014-02-15 22:11:30
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: c++ priority-queue


    【解决方案1】:

    初始化并不能确定优先级队列的操作方式。如果您希望它以特定方式排序,您有两种选择。

    第一个选项是在您的 Node 对象上定义 &lt; 运算符,以便按照您想要的方式比较它们。

    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;
    

    【讨论】:

    • 我很想知道:在每个节点中包含comparator,特别是当节点很大时,会导致任何性能问题吗?
    • 函数不占用对象内部空间。
    • 是的,我也很好奇 Node.js 中 operator
    【解决方案2】:

    你可以使用:

    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::push)时,该元素会自动放置在正确的位置吗?

    是的。

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

    【讨论】:

    • 哦,我明白了。所以你必须传入一个比较器?谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多