首页 > 解决方案 > 排序功能对我的班级进行排序

问题描述

#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 *'

我不明白,请帮助我。

标签: c++function

解决方案


要修复该错误,您应该更改cmpfrom的签名

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<for Student,你根本不需要这个函数,你可以简单地调用

std::sort(students.begin(), students.end());

推荐阅读