0

I'm working on a student information system so that I have this struct to store student information:

struct student_info
{
   string name;
   int id;
   string course;
   int percent;
};

I have also made this sorting function:

bool sorting(const container &a, const container &b) {
    return a.percent < b.percent;
}

Here, I read from a file and store in the struct, push it into the vector of struct and then sort it:

student_info raw_data;
vector <student_info> container;

ifstream infile("data.txt");

while(!infile.eof())
{
   infile >> raw_data.name >> raw_data.id >> raw_data.course >> raw_data.percent;  
   container.push_back(raw_data);
}   

sort(container.begin(), container.end(), sorting);

Then, I saw this somewhere but it didn't clearly explain why I don't need brackets even though sorting is a function like why is it just sorting and not sorting() when sort is called?

Vishaal Shankar
  • 1,603
  • 12
  • 25
  • 1
    [Why is `iostream::eof` inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – O'Neil Feb 09 '18 at 06:35
  • 1
    `sorting` isn't called there, thus no brackets. `std::sort` will call it later. – molbdnilo Feb 09 '18 at 06:44

2 Answers2

3

The name of the function is sorting. The expression sorting(a, b) would call sorting and return a bool. The sort routine std::sort will call sorting that way many times.

The name is not a good one. I would suggest percent_less_than rather than 'sorting'. Furthermore, the parameterization is wrong. It compares the percent of students.

bool percent_less_than(const student_info &a, const student_info &b) {
    return a.percent < b.percent;
}
Jive Dadson
  • 15,176
  • 9
  • 47
  • 65
2

Jive Dadson correctly responded to your question. You can also use lambda syntax for sorting.

sort(container.begin(), container.end(), [=](const student_info &a, const student_info &b) {
    return a.percent < b.percent;
});
Tazo leladze
  • 1,026
  • 10
  • 21