前提:
学生结构体
实现自定义顺序输出
typedef struct student {
int grade;
char name[100];
int year;
} student;
①重写构造函数-字符数组形参的传递
char* name:可写的
const char* name:只读的
区别:strcpy与strcmp
student(int grade, const char* name,int year) {
this->grade=grade;
strcpy(this->name,name);
this->year=year;
}
②重载运算符
类内重载
1,只能有一个参数,注意const和&
2,参数括号后面加一个const
typedef struct student {
int grade;
char name[100];
int year;
bool operator< (const student &b) const{
if(this->grade==b.grade) {
int x=strcmp(this->name,b.name);
if(x==0) return this->year<b.year;
else return x>0;
} else
return this->grade>b.grade;
}
} student;
类外重载
1,两个参数,注意const和&
2,友元函数friend
typedef struct student {
int grade;
char name[100];
int year;
friend bool operator< (const student &a, const student &b);
} student;
bool operator< (const student &a, const student &b) {
if(a.grade==b.grade) {
int x=strcmp(a.name,b.name);
if(x==0) return a.year<b.year;
else return x>0;
} else {
return a.grade>b.grade;
}
}
③priority_queue中的用法
#include <bits/stdc++.h>
using namespace std;
typedef struct student {
int grade;
char name[100];
int year;
student(int grade, const char* name,int year){
this->grade=grade;
strcpy(this->name,name);
this->year=year;
}
} student;
bool operator< (const student &a, const student &b) {
if(a.grade==b.grade) {
int x=strcmp(a.name,b.name);
if(x==0) return a.year<b.year;//year小在后
else return x>0;//name大在后
} else {
return a.grade>b.grade;//grade大则返回true,则<,则优先级低,则在后
}
}
int main() {
priority_queue<student> q;
q.push(student(10,"ab",4));
q.push(student(10,"ac",7));
q.push(student(10,"ac",2));
q.push(student(11,"xx",4));
while(!q.empty()){
student stu=q.top();
cout<<stu.grade<<" "<<stu.name<<" "<<stu.year<<endl;
q.pop();
}
}
输出
10 ab 4
10 ac 7
10 ac 2
11 xx 4
④sort的用法
#include <bits/stdc++.h>
using namespace std;
typedef struct student {
int grade;
char name[100];
int year;
student(int grade, const char* name,int year) {
this->grade=grade;
strcpy(this->name,name);
this->year=year;
}
bool operator< (const student &b) const{
if(this->grade==b.grade) {
int x=strcmp(this->name,b.name);
if(x==0) return this->year<b.year;//year小在前
else return x>0;//name大在前
} else {
return this->grade>b.grade;//grade大在前
}
}
} student;
int main() {
student stu[4]={{10,"ab",4},{10,"ac",7},{10,"ac",2},{11,"xx",4}};
sort(stu,stu+4);
for(int i=0;i<4;i++){
cout<<stu[i].grade<<" "<<stu[i].name<<" "<<stu[i].year<<endl;
}
}
输出
11 xx 4
10 ac 2
10 ac 7
10 ab 4
结论:sort与priority_queue相反