Как правильно сделать сортировку списка list?
У меня есть список list с объектами класса Student. Вот сам класс:
#pragma once
#include <iostream>
using namespace std;
class student
{
private:
string name;
int age;
string clas;
string dateBirth;
public:
student(string name_m, int age_m, string class_m,string dateBirth);
~student() {};
void show();
friend ostream& operator<< (std::ostream& out, const student& strudent_m);
string getName();
string getClas();
};
#include "Student.h"
student::student (string name_m, int age_m, string class_m, string dateBirth_m)
{
this->name = name_m;
this->age = age_m;
this->clas = class_m;
this->dateBirth = dateBirth_m;
}
ostream& operator<< (std::ostream& out, const student& strudent_m)
{
out << strudent_m.name << endl;
out << strudent_m.dateBirth << endl;
out << strudent_m.age << endl;
out << strudent_m.clas<< endl;
return out;
}
string student::getName()
{
return (this->name);
}
string student::getClas()
{
return (this->clas);
}
void student:: show()
{
cout<<"Имя фамилия ученика: " <<this->name << endl;
cout << "Дата рождения: " << this->dateBirth << endl;
cout << "Возраст: " << this->age << " лет"<<endl;
cout << "Класс обучения: " << this->clas << endl;
}
Хочу сделать сортировку по переменной string clas. Гуглил эту тему. Написал компаратор, почему то вылетает с ошибкой "Invailed comparator". Вот мой код, которым я пытался сравнивать:
bool compare_clas(student& first, student& second)//Компаратор сам
{
int i = 0;
while (i < 2)
{
if (first.getClas()[i] < second.getClas()[i])
return true;
else if (first.getClas()[i] > second.getClas()[i])
return false;
++i;
}
return true;
}
list1.sort( compare_clas);
list<student>::iterator it = list1.begin();
for (list<student>::iterator it = list1.begin(); it != list1.end(); ++it)
(*it).show();
break;
Ответы (1 шт):
Автор решения: Qwertiy
→ Ссылка
Потому что твой компаратор всегда возвращает true.
А должен возвращать true только если первый меньше.
И ещё ты вместо const-ссылок написал обычные, но VS тебе это порстила.