0

I have a class Student with 2 member variables, one of which is grade. I create some students by the corresponding constructors and then put them in a list<Student>. I then want to use the sort() method in the stl <algorithm> library and sort the students by their grade not by their names. However I do not know how can I tell this to the sort() function - should I use another parameter or there is some other method?

#include <iostream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
class Student {
    string name;
    double grade;
public:
    Student(string n, double g) {
        name = n;
        grade = g;
    }
    double getGrade() {
        return grade;
    }
};
int main()
{
    list<Student> sp;
    Student s1("Steve", 4.50), s2("Peter", 3.40), s3("Robert", 5);
    sp.push_back(s1);
    sp.push_back(s2);
    sp.push_back(s3);
    //I want to sort the list by the student's grades - how can I tell this to the sort() method?
    sort(sp.begin(), sp.end());

}
A.Antonov
  • 37
  • 3
  • 1
    If you want to use `std::sort` then you need `std::vector` like container and then this would be a dupe of: https://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects – NathanOliver Oct 26 '18 at 14:40

1 Answers1

1

Provide a predicate to sort. And change sp to be a std::vector. A lambda will do nicely:

std::sort(sp.begin(), sp.end(), 
    [](const auto& lhs, const auto& rhs) {
        return lhs.getGrade() < rhs.getGrade();
    });
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70