Функция сортировки для сортировки my-class - PullRequest
0 голосов
/ 15 мая 2018
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <stack>
#include <list>
#include <queue>
#include <deque>
#include <set>
#include <algorithm>
#include <iterator>
#include <map>
#include <sstream>
#include <cmath>
using namespace std;
class Student
{
private:
    int age;
    string name;
public:
    Student(){ }
    ~Student() { }
    friend istream & operator >> (istream& in, Student & a);
    friend ostream & operator << (ostream& out, const Student & a);
    bool operator > (Student& a)
    {
        if (age != a.age)
            return age > a.age;
        else
            return name > a.name;
    }
};
istream & operator >> (istream& in, Student & a)
{
    in >> a.name >> a.age;
    return in;
}
ostream & operator << (ostream& out, const Student & a)
{
    out << a.name << " " << a.age;
    return out;
}
bool cmp( Student *a,Student *b)
{
    return (*a) > (*b);
}
int main()
{
    Student stu;
    vector<Student> students;
    while (cin >> stu) {
        students.push_back(stu);
    }
    sort(students.begin(), students.end(), cmp);
    return 0;
}

Я определил класс. Но когда я использовал функцию сортировки для сортировки, она пошла не так, как

No viable conversion from 'Student' to 'Student *'

Я не понимаю, пожалуйста, помогите мне.

Ответы [ 2 ]

0 голосов
/ 15 мая 2018

<algorithm> использует operator <, а не operator >. поэтому ваш класс стал (const фиксированным):

class Student
{
private:
    int age;
    string name;
public:
    Student(){}
    ~Student() {}
    friend istream & operator >> (istream& in, Student & a);
    friend ostream & operator << (ostream& out, const Student & a);
    bool operator < (const Student& rhs) const
    {
        return std::tie(age, name) < std::tie(rhs.age, rhs.name);
    }
};

Предикат должен иметь подпись, «совместимую» с bool cmp(const Student&, const Student&), ваша функция cmp не соответствует.

Чтобы отсортировать в порядке убывания, вам просто нужно сделать:

std::sort(students.begin(), students.end(), std::greater<>{});

Для возрастания:

std::sort(students.begin(), students.end());
0 голосов
/ 15 мая 2018

Чтобы исправить эту ошибку, вы должны изменить сигнатуру cmp с

bool cmp( Student *a,Student *b)
{
    return (*a) > (*b);
}

на

bool cmp(Student const& a, Student const& b)
{
    return a < b;  // Note std::sort uses operator< for comparison
}

Однако, если вы просто определите operator< для Student, вам вообще не нужна эта функция, вы можете просто вызвать

std::sort(students.begin(), students.end());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...