c++ - 排序功能对我的班级进行排序
问题描述
#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 *'
我不明白,请帮助我。
解决方案
要修复该错误,您应该更改cmp
from的签名
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());
推荐阅读
- angular - 是否可以将当前日期和时间放在 mat-form-field 中?
- abp - 如何从代码后面设置 ABP 模态对话框的结果?
- python - 如何替换altair中的轴标签?
- specifications - systemRDL 寄存器组件属性中的黑白“内部”和“外部”差异
- javascript - Discord.js Bot 无法处理同一频道中的多个按钮(版本 13)
- go - Gazelle 为工作区中的特定子目录生成脚本
- jwt - JWT 令牌加密
- node.js - 谷歌电子表格 API 返回一个页面说地址尚未找到
- python - How to use Pandas sep when including time information?
- python - 如何前往网站的下一页 我在导航到下一页时遇到问题