I am currently trying to sort a list of objects in this case students, based on their grades, student number, name, etc.
listOfStudents.sort([](const Students& student1, const Students& student2)
{
if (student1.getStudentNumber() == student2.getStudentNumber())
return student1 < student2;
return student1.getStudentNumber() < student2.getStudentNumber();
});
This is the code I am currently using to sort the list based on their student number but it points an error to the student1 and student2 saying "The object has type qualifiers that are not compatible".
Here is the code for the Student Class:
class Students {
int studentNumber;
string studentName;
int grade1;
int grade2;
int grade3;
int grade4;
int grade5;
int total;
public:
void setStudent(int number, string name, int g1, int g2, int g3, int g4, int g5, int total) {
this->studentNumber = number;
this->studentName = name;
this->grade1 = g1;
this->grade2 = g2;
this->grade3 = g3;
this->grade4 = g4;
this->grade5 = g5;
this->total = total;
}
int getStudentNumber() {
return this->studentNumber;
}
string getStudentName() {
return this->studentName;
}
int getGrade1() {
return this->grade1;
}
int getGrade2() {
return this->grade2;
}
int getGrade3() {
return this->grade3;
}
int getGrade4() {
return this->grade4;
}
int getGrade5() {
return this->grade5;
}
int getTotal() {
return this->total;
}
};
and this is the implementation part
list <Students> listOfStudents;
Students students;
The above codes are currently producing errors about the list type qualifiers etc.
Did I miss something? Im sure I did. Thank you in advance for relieving my idiocy.
CodePudding user response:
int getStudentNumber() {
return this->studentNumber;
}
should be
int getStudentNumber() const {
return this->studentNumber;
}
and the same for all the other getters in your code.
CodePudding user response:
Okay, so I've read some comments. and yes I forgot to make the <() operator. I knew I had missed something.
and also making the getters const is important, and apparently, I forget them as well.
Here is the updated code and it is now working. Thanks, everyone.
In the Student Class:
bool operator <(const Students& studentObj) const {
return this->getStudentNumber() < studentObj.getStudentNumber();
}