2014-10-05 86 views
-2

我不知道如何实现priority_queue,比较对象的整数字段时,很明显。 例如C++ STL 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; 你能给我一个主意吗?

+0

我建议您阅读例如[这个'std :: priority_queue'引用](http://en.cppreference.com/w/cpp/container/priority_queue),它包含一个链接,指向比较函数需要什么的确切定义。 – 2014-10-05 11:02:42

+1

你有两个代表彼此完全相反的属性吗?如果是这样,那么首先将其减少到一个属性。然后,使用std :: less 来比较该属性,即将包含对象的比较委托给其中的根据字段的比较。 – 2014-10-05 11:04:53

+2

请澄清你的问题。这个贵宾僵硬没有任何意义。 – juanchopanza 2014-10-05 11:36:49

回答

0

你的问题有点不清楚。我假设你想要分类的结构是Toast

如果你只是想根据boolToast s到优先,说status,你的比较对象是很容易的:

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

现在我要承担以下就此展开,给出Toast有以下bool成员最显著的顺序排列,至少显著:vipnotvip,VIP1 ,的Vip3 , and notVip2`,我还假设在比较“不”的成员应该被反转:

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 
    } 
}; 

注意,如果构件是bool S或operator<operator>operator==被定义为其中任何其它类型的任一这些mycomparison类的工作正常。要在std::priority_queue中使用mycomparision,您只需要将其作为std::priority_queue的比较对象传递给它,例如:std::priority_queue<Toast> foo(mycomparison());