【问题标题】:operator< error in priority queue [duplicate]运算符<优先级队列中的错误[重复]
【发布时间】:2016-05-17 21:34:11
【问题描述】:

我正面临“二进制 '

我也想问如何通过baloon.end来排序优先队列?

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

class Baloons
{
public:
    float start;
    float end;

public:
    Baloons() {}
    Baloons(float start, float end) : start{ start }, end{ end } {}
};

int main()
{
Baloons baloon1(1, 5);
Baloons baloon2(4, 7);
Baloons baloon3(6, 9);
Baloons baloon4(11, 12);
std::priority_queue<Baloons> myBaloons;
myBaloons.push(baloon1);
myBaloons.push(baloon2);
myBaloons.push(baloon3);
myBaloons.push(baloon4);
while (!myBaloons.empty())
{
    Baloons b = myBaloons.top();
    cout << b.start << " -> " << b.end << " ";
    myBaloons.pop();
}
system("pause");
return 0;

}

【问题讨论】:

  • 考虑到标准集合和算法中使用了多少&lt;,我实际上很惊讶stackoverflow.com/… 没有得到具体结果...

标签: c++ stl priority-queue


【解决方案1】:

你需要为你的气球类添加一个operator&lt;,例如:

bool operator<(const Baloons& rhs) const {
  return std::make_pair(start,end) < std::make_pair(rhs.start,rhs.end);
}

它将用于对集合中的元素进行排序

【讨论】:

  • 感谢您帮助我,感谢您没有将我的问题作为家庭作业来判断。
【解决方案2】:

您需要为Baloons 提供重载的operator&lt;,否则编译器不知道如何对std::priority_queue&lt;Baloons&gt; 的元素进行排序。例如,在 Baloons 类中定义如下内容:

bool operator<(const Baloons& _other) const {
    return end < _other.end;
}

或者您想在此处比较 return 语句的任何内容。

【讨论】:

    【解决方案3】:

    提供bool operator &lt; (const Baloons&amp;, const Baloons&amp;)

    bool operator < (const Baloons& lhs, const Baloons& rhs)
    {
        return lhs.end < rhs.end;
    }
    

    或创建一个函子CustomComparer 并将其提供给std::priority_queue&lt;Ballons, std::vector&lt;Ballons&gt;, CustomComparer&gt;

    struct CustomComparer
    {
        bool operator () (const Baloons& lhs, const Baloons& rhs) const
        {
            return lhs.end < rhs.end;
        }
    };
    

    以后

    std::priority_queue<Ballons, std::vector<Ballons>, CustomComparer> myBaloons;
    

    【讨论】:

      【解决方案4】:

      优先级队列是已排序的容器,但编译器不知道如何对Baloons 进行排序。你必须定义一个自定义的operator&lt;,这样你的容器才能被排序。

      这显然是一个家庭作业问题(很确定这只是为了“myBalons.pop()”的玩笑而创建的)所以我不想放弃整个事情......将这样的东西添加到你的 Baloons 类.

      bool operator<(const Baloons& rhs) const {
          // return true if this Baloons is less than 'rhs'
      }
      

      这样你的气球就可以比较了。 (例如if (baloon1 &lt; baloon2) { /* do stuff */ })当您插入新对象时,优先级队列会在幕后进行这种比较。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-21
        • 1970-01-01
        • 1970-01-01
        • 2015-10-07
        • 2016-06-17
        • 1970-01-01
        相关资源
        最近更新 更多