【问题标题】:C++ STL priority_queue , the way to compare objectsC++ STL priority_queue ,比较对象的方式
【发布时间】:2014-10-05 10:58:05
【问题描述】:

我不知道如何实现priority_queue,在比较对象整数字段时,很清楚。 例如

bool operator()(const Toast &t1, const Toast &t2) const
{
    int t1value = t1.bread * 1000 + t1.butter;
    int t2value = t2.bread * 1000 + t2.butter;
    return t1value < t2value;
}

这将根据值将对象放入堆中。 问题是如何根据布尔字段比较对象?如何根据布尔类型存储多个对象? 例如 : vip=true,notvip=false; Vip1 , notVip2, Vip3.
结果应该是:Vip1,Vip3,notVip2; 你能给我一个想法吗?

【问题讨论】:

  • 我建议你阅读例如this std::priority_queue reference,它包含指向比较函数所需内容的确切定义的链接。
  • 您是否有两个代表完全相反的属性?如果是这样,请先将其减少为一个属性。然后,使用 std::less 比较属性,即将包含对象的比较委托给内部相应字段的比较。
  • 请澄清您的问题。这个vip僵硬没有任何意义。
  • ok 如果我这样做 if(c1.status == true && c2.status== false ) return c1.status>c2.status; ,我会得到一个错误,它不会存储我的对象;我需要先存储真然后存储假;
  • 再一次,你的问题毫无意义。什么是“商店”?这意味着什么?什么是“c1”,什么是“c2”?您发布的示例代码没有任何名为“c1”或“c2”的内容。每次你试图解释你的问题时,你都会抛出一些以前没有提到过的新东西。从别人那里得到正确答案的诀窍是正确地解释自己。

标签: c++ stl priority-queue


【解决方案1】:

你的问题有点不清楚。我将假设您要排序的结构是Toast

如果您只是想根据boolToasts 进行优先级排序,比如status,那么您的比较对象非常简单:

class mycomparison
{
public:
    bool operator() (const Toast& lhs, const Toast& rhs) const
    {
        return lhs.status < rhs.status;
    }
};

现在我将假设以下内容对此进行扩展,因为Toast 有以下bool 成员按最重要到最不重要的顺序列出:vipnotvip、Vip1, Vip3, andnotVip2`,我还假设“非”成员的比较应该倒置:

class mycomparison
{
public:
    bool operator() (const Toast& lhs, const Toast& rhs) const
    {
        return lhs.vip < rhs.vip || lhs.vip == rhs.vip && // return true if rhs.vip is the only true or continue to test
             ( lhs.noVip > rhs.noVip || lhs.noVip == rhs.noVip && // return true if rhs.noVip is the only false or continue to test
             ( lhs.Vip1 < rhs.Vip1 || lhs.Vip1 == rhs.Vip1 && // return true if lhs.Vip1 is less than rhs.Vip1 or continue to test
             ( lhs.Vip3 < rhs.Vip3 || lhs.Vip3 == rhs.Vip3 && // return true if lhs.Vip3 is less than rhs.Vip3 or continue to test
               lhs.notVip2 > rhs.notVip2 ) ) ); // return true if lhs.notVip2 is greater than rhs.notVip2 or return false
    }
};

请注意,如果成员是 bools 或定义了 operator&lt;operator&gt;operator== 的任何其他类型,则这些 mycomparison 类中的任何一个都可以正常工作。要在std::priority_queue 中使用mycomparision,您只需将其作为std::priority_queue 的ctor 中的比较对象传递,例如:std::priority_queue&lt; Toast &gt; foo( mycomparison() );

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多