有些时候要用char型的数组来储存学号、证件号,这时候的排序就不能简单的用比较大小的方式来完成了。
可以使用C语言头文件#include<string.h>的库函数: strcmp(str_1,str_2)来完成
在结构体里重载了运算符>
下面是strcmp的简单使用及冒泡排序
typedef struct Student {
char id_number[11] = { '\0' };
char name[7] = { '\0' };
char m_grade[4] = { '\0' };
char e_grade[4] = { '\0' };
int operator>(Student& other) {
char* id_1, *id_2;
id_1 = id_number;
id_2 = other.id_number;
if (strcmp(id_1,id_2)>0) {
return 1;
}
else {
return 0;
}
}
}Stu;
void swap(Stu& other, Stu& another) {
Stu temp;
temp = other;
other = another;
another = temp;
}
void bubble_sort(Stu *students,int &length) {
int i, j;
if (length > 1) {
for (i = 0; i < length; i++) {
for (j = i + 1; j < length; j++) {
if ((students[i] > students[j]) == 1) {
swap(students[i], students[j]);
}
}
}
}
}