stl priority_queue of C with struct

新手上路,请多包涵

我们如何将 STL priority_queue 用于 struct ?任何关于 push & popping 的 说明,其中 struct 有多种数据类型?

说: struct thing { int a; char b;} glass[10];

现在我如何使用’int a’将这个结构放在priority_queue上进行排序?

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

阅读 377
1 个回答

这是对 您原始问题的略微修改的答案,您无缘无故地删除 了该答案。原件包含足够的信息让您弄清楚这一点,但在这里:提供一个小于比较,使用 int 进行比较。

您需要做的就是提供一个函子,该函子通过严格的弱排序实现小于比较,或者为您的类实现相同的小于运算符。该结构满足要求:

 struct thing
{
    int a;
    char b;
    bool operator<(const thing& rhs) const
    {
        return a < rhs.a;
    }
};

然后

std::priority_queue<thing> q;
thing stuff = {42, 'x'};
q.push(stuff);
q.push(thing{4242, 'y'}); // C++11 only
q.emplace(424242, 'z'); // C++11 only
thing otherStuff = q.top();
q.pop();

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

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