我目前在std::functional中偶然发现了std::greater、std::lesser等类。
如您所见,这些类与 <> 一起使用,因此它们可以与任何数据类型一起使用。因此,我试图通过重载 bool 运算符使这些类“正确”识别顺序。
但是,这是我尝试过的,但没有正常工作。
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
class MyClass
{
public:
MyClass(int x, std::string str) {(*this).x = x; (*this).str = str;}
int getInt()const{return (*this).x;}
std::string getStr(){return this->str;}
bool operator <(const MyClass& ot)const{return (*this).getInt() < ot.getInt();}
bool operator >(const MyClass& ot)const{return (*this).getInt() > ot.getInt();}
private:
int x;
std::string str;
};
int main()
{
std::priority_queue<MyClass*,std::vector<MyClass*>,std::less<MyClass*> > MinQ;
std::priority_queue<MyClass*,std::vector<MyClass*>,std::greater<MyClass*> > MaxQ;
MyClass *m = new MyClass(1,"one");
MinQ.push(m); MaxQ.push (m);
m = new MyClass(36,"thirty six");
MinQ.push(m); MaxQ.push (m);
m = new MyClass(47,"forty six");
MinQ.push(m); MaxQ.push (m);
m = new MyClass(1,"first");
MinQ.push(m); MaxQ.push (m);
m = new MyClass(2,"second");
MinQ.push(m); MaxQ.push (m);
m = new MyClass(2,"two");
MinQ.push(m); MaxQ.push (m);
m = new MyClass(7,"seven");
MinQ.push(m); MaxQ.push (m);
m = new MyClass(28,"twenty eight");
MinQ.push(m); MaxQ.push (m);
while(!MinQ.empty())
{
std::cout<<MinQ.top()->getStr()<<std::endl; MinQ.pop();
}
std::cout<<"------------------------------------------------"<<std::endl;
while(!MaxQ.empty())
{
std::cout<<MaxQ.top()->getStr()<<std::endl; MaxQ.pop();
}
}
结果:
twenty eight
seven
two
second
thirty six
forty six
first
one
------------------------------------------------
one
first
forty six
thirty six
second
two
seven
twenty eight
有人可以给我关于这个的解释和/或给我关于这样做的正确方法的建议吗?