我目前偶然发现了std::functional中的std::great、std::less等类。
正如您所看到的,这些类带有<>以便它们可以与任何数据类型一起使用。因此,我试图通过重载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
有人能给我解释一下和/或给我正确的方法建议吗?
问题是在数据结构中使用指针,而不是对象。
有两种解决方案:要么编写一个对指针有效的函子:
struct Greater
{
bool operator()(MyClass *a, MyClass *b) const
{
return *a > *b;
}
};
std::priority_queue<MyClass*,std::vector<MyClass*>, Greater > MaxQ;
要么直接使用对象(我强烈推荐这种方法,但它并不总是适用的)。
std::priority_queue<MyClass,std::vector<MyClass>, std::less<MyClass> > MinQ;