在Priority_Queue中订购

时间:2017-04-07 18:55:08

标签: queue priority-queue

我正在尝试学习如何使用priority_queue与队列。我有一个priority_queue的代码,它应该从用户那里得到输入。输入是家务活和杂务的优先号。他们可以根据需要输入任意数量,并且应该按顺序输出它们。我的问题是它没有按顺序输出它们。我不确定它是在我的主人身上还是在我的重载身上<操作员功能。这是我的Chore.h代码:

#include<iostream>
#include<fstream>
using namespace std;
//#ifndef CHORE_H;
//#define CHORE_H;

class Chore{
public:
    Chore(){priorityNum=0;choreName="";}
    std::string getName (Chore c1)const{return choreName;}
    int getPriorityNum(Chore c1)const{return priorityNum;}
    bool operator <(const Chore c1)const;
    std::ostream& output(std::ostream& cout,const Chore c)const;
    std::istream& input(std::istream& cin);
private:
    std::string choreName;
    int priorityNum;
};
//#endif

这是我的Chore.cc代码:

#include"Chore.h"
using namespace std;

bool Chore::operator <(const Chore c1)const{
Chore c2;
int c1Num=c1.getPriorityNum(c1);
int c2Num=c2.getPriorityNum(c2);
return c1Num<c2Num;
/*if(c1Num<c2Num)
    return true;

else if(c1Num==c2Num)
    return true;

else
    return false;*/
}

std::ostream& Chore::output(std::ostream& cout,const Chore c)const{
cout<<endl<<"Chore: "<<getName(c)<<endl;
cout<<"chore Priority: "<<getPriorityNum(c); 
}

std::istream& Chore::input(std::istream& cin){
cout<<endl<< "Enter chore name:";
cin >>choreName;
cout<<endl<<"Enter priority number:";
cin >>priorityNum;
}

我的主要内容如下:

#include<queue>
#include<iostream>
#include"Chore.h"
using namespace std;

int main(){
std::priority_queue<Chore>myChores;
Chore tmp;
bool enterAnother=true;

//input loop
while(enterAnother){
    char c;//checks if they want to continue
    tmp.input(cin);
    myChores.push(tmp);
    cout<<endl<<"Want to enter another chore?(y for yes, n for no)";
    cin >>c;
    if(c=='y'|| c=='Y')
        enterAnother=true;
    else
        enterAnother=false;
}

//output loop
while(!myChores.empty()){
    tmp = myChores.top();
    myChores.top().output(cout,tmp);
    myChores.pop();
}
}

非常感谢任何帮助。

0 个答案:

没有答案