1
我目前正在std :: functional std :: std :: std :: lesser等std ::類中尋找類。如何正確使用std :: functional爲其他數據類型(在優先級隊列中)
正如你所看到的,這些類是<>,以便它們可以用於任何數據類型。 所以,我試圖讓這些類「正確地」通過重載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
能有人給我解釋這個和/或給我的建議對這樣做的正確方法?
最後,我得到了這個工作,謝謝! –