Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a list of objects by property in C++ using the standard list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

int getStudentNumber() {
    return this->studentNumber;
}

should be

int getStudentNumber() const {
    return this->studentNumber;
}

and the same for all the other getters in your code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading