【发布时间】:2014-12-29 18:30:24
【问题描述】:
我正在创建一个种族的 c++ 程序。
我有比赛课。每场比赛都有一个名称、一个距离和一个结果指针向量(它是每个参与者的一个结果)。
结果类有一个指向参与者的指针和一个时间。
上课时间有小时、分钟和秒。
我想将结果向量从最快到最慢排序,所以为了比较结果,我在result 类中创建了函数bool operator <(Result& res2) const。
.h文件中的所有功能都实现了,我就不一一展示了。
我几乎可以肯定函数 sortResults 不正确,但函数 operator< 给了我不知道如何解决的错误。它在所有 if 语句中都给了我这个错误:此行有多个标记
- passing 'const Time' as 'this' argument of 'unsigned int Time::getHours()' discards qualifiers [-
fpermissive]
- Line breakpoint: race.cpp [line: 217]
- Invalid arguments ' Candidates are: unsigned int getHours() '
你能告诉我我做错了什么吗?
.h 文件:
class Time
{
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
public:
Time(unsigned int h, unsigned int m, unsigned int s, unsigned int ms);
Time();
unsigned int gethours();
unsigned int getMinuts();
unsigned int getSeconds();
string show();
};
class Participant {
string name;
unsigned int age;
string country;
public:
Participant(string n, unsigned int a, string c);
string getName();
string getCountry();
int getAge();
string show() const;
};
class Result {
Participant *part;
Time time;
public:
Result(Participant *p, Time t);
Participant *getParticipant() const;
Time getTime();
string show();
bool operator <(Result& res2) const;
};
class Race {
string name;
float distance;
vector<Result *> results;
public:
Race(string nm, float dist);
string getName();
void setName(string nm);
float getDistance();
vector<Result *> sortResults();
void addResult(Result *r);
string showRaceResults();
string show();
};
.cpp 文件:
bool Result::operator <(Result& res2) const {
if (time.gethours() < res2.getTime().gethours())
return true;
else {
if (time.gethours() > res2.getTime().gethours())
return false;
else {
if (time.getMinutes() < res2.getTime().getMinutes())
return true;
else {
if (time.getMinutes() > res2.getTime().getMinutes())
return false;
else {
if (time.getSeconds() < res2.getTime().getSeconds())
return true;
else {
return false;
}
}
}
}
}
}
vector<Result *> Race::sortResults() {
sort (results.begin(), results.end(), operator <);
return results;
}
【问题讨论】:
-
拜托,哦,请删除
operator<中的所有else垃圾。你的函数看起来会更好。 -
点赞
bool Result::operator <(Result& rhs) const { return std::make_tuple(time.gethours(), time.getMinutes(), time.getSeconds()) < std::make_tuple(rhs.time.gethours(), rhs.time.getMinutes(), rhs.time.getSeconds()); }; -
使用运算符对向量进行排序是否正确?或者我应该创建一个类似的函数:bool Result::lowerTime(Result& res1, Result& res2) const,对结果向量进行排序?最好的方法是什么?
标签: c++ sorting pointers object vector