排序函数来排序我的类

时间:2018-05-15 12:23:14

标签: c++ function

The connection to the server xx.xx.xx.xx was refused - did you specify the right host or port?

我定义了一个类。但是当我使用sort函数对它进行排序时,它就像

一样出错了
#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;
}

我不明白,请帮帮我。

2 个答案:

答案 0 :(得分:1)

要修复该错误,您应该从

更改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());

答案 1 :(得分:1)

<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());