构造向量的优先级队列

新手上路,请多包涵

我正在寻找向量优先级队列的简单 STL 实现。每个向量正好有 4 个元素。我想根据每个向量的第三个元素对我的优先级队列进行排序。具有最低第 3 个元素的向量应位于顶部(向量的最小优先级队列)。

如何在 C++ 中实现这一点?

另外,如果有人有默认优先级队列的实际 STL 实现,请提供链接。就像STL里面的官方实现一样。

原文由 as2d3 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 358
1 个回答

您必须创建自己的 比较器 来比较 priority_queue 的元素。

像这样的东西:

 // How to compare elements
struct my_comparator
{
    // queue elements are vectors so we need to compare those
    bool operator()(std::vector<int> const& a, std::vector<int> const& b) const
    {
        // sanity checks
        assert(a.size() == 4);
        assert(b.size() == 4);

        // reverse sort puts the lowest value at the top
        return a[2] > b[2];
    }
};

// for usability wrap this up in a type alias:
using my_priority_queue = std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, my_comparator>;

int main()
{
    my_priority_queue mpq;

    mpq.push({1, 2, 1, 4});
    mpq.push({1, 2, 2, 4});
    mpq.push({1, 2, 3, 4});

    // etc ...
}

原文由 Galik 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏