#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stdio.h>
using namespace std;
class Complex
{
public:
double Re;
double Im;
double mo;
void Input()
{
scanf("%lf+i%lf",&Re,&Im);
mo = sqrt(Re*Re + Im*Im);
}
void Show() const
{
printf("%.0lf+i%.0lf\n",Re,Im);
}
bool operator < ( const Complex &c2) const
{
if(this->mo != c2.mo)
return this->mo<c2.mo;
else
return this->Im>c2.Im;
}
};
int main()
{
int n,i;
string temp;
cin>>n;
priority_queue<Complex,vector<Complex>,less<Complex> >q;
string Pop = "Pop",Insert = "Insert";
for(i=0;i<n;i++)
{
cin>>temp;
if(temp == Insert)
{
Complex temp;
temp.Input();
q.push(temp);
cout<<"SIZE = "<<q.size()<<endl;
}
else
{
if(q.empty())
cout<<"empty"<<endl;
else
{
q.top().Show();
q.pop();
cout<<"SIZE = "<<q.size()<<endl;
}
}
}
return 0;
}
一、類中重載運算符
一般有兩種方法,一是定義一個友元函數,參數爲兩個類對象。
二是用此方法,模板是:
返回值類型 operator @ (參數列表)
{
}
如果是一個雙目運算符(需要兩個類的對象參與的),在參數列表裏需要添加另一個類的對象。
例如本題中:
bool operator < ( const Complex &c2) const
在執行 c1 < c2時,相當於將 c2 作爲參數傳入到了該成員函數中。
另一個參數使用引用類型
const表示此函數不會對類的屬性進行修改,如果要使用優先隊列等容器時要加上const。
二、類在優先隊列中的使用
priority_queue<Complex,vector<Complex>,less<Complex> >q;
重載運算符時 屬性必須加上const
方法和基本類型相同,該類必須重載<,>運算符才能使用優先隊列。
重載<可使用less,重載>可使用greater;
三、對於const的一點理解
對於定義爲const的變量,是不允許對其進行修改的。同理,對於類中定義爲const的成員函數,不允許其對類的屬性進行修改,所以在定義類的成員函數時,如果該函數未對類進行修改,儘量在成員函數定義後加上const。
同時,定義爲const的類的變量,只能調用類中定義爲const的成員函數。
在本例中,一開始Show()函數未定義爲const屬性,q.top().Show()會報錯,因爲top()返回的是一個const引用,無法調用Show()函數,將Show()屬性改爲const後即可正常使用.