实现
对自定义数据类型Person进行排序,Person类包括姓名、成绩、年龄等成员属性。
排序规则:先按成绩降序排序,再按年龄升序排序。
示例:自定义数据类型Person的排序
手把手教....
1.构建一个结构体,并创建一个结构体数组,数组里那个N是用define声明的!
struct student
{
char name[20];
int age=0;
int score=0;
}a[N];
2.定义一个结构体类型的变量list <student> L;
3.既然是排列,这里当然是写关于结构体的排序
bool cmp(student a, student b)
{
if(a.score!=b.score)
return a.score > b.score; //成绩降序排列
else if (a.age != b.age)
{
return a.age > b.age; //年龄降序排列
}
int tmp = strcmp(a.name, b.name);
if (tmp != 0)
return tmp < 0;
}
这里cmp函数的参数是student类的变量,上一篇写的是const void*....因为不太会用const void*才直接定义了student类
特别声明一下对于用数组进行排序的!
int tmp = strcmp(a.name, b.name);
if (tmp != 0)
return tmp < 0;
如果(a.name=b.name)tmp就是等于1,反之则等于0;如果等于零,进行降序排列
4.我在这是写一个函数,把数值从键盘输入,并调用排序函数
void enion() //入链函数
{
//list <student> L1;
for (int i = 0; i < N; i++)
{
cin >> a[i].name;
cin >> a[i].age;
cin >> a[i].score;
L.push_back(a[i]);
}
cout << "===================我是分隔符====================" << endl;
cout << "原值:" << endl;
printList(L);
L.sort(cmp);
}
5.写一个输出函数...就是第四步调用的printList.
emmmm....以后有新学会的会进一步补充
粘一下运行结果
好了,接下来就是源码
#include<iostream>
#include<list> //添加list类头函数
#define N 5
using namespace std;
struct student
{
char name[20];
int age=0;
int score=0;
}a[N];
list <student> L;
void enion();
void printList(const list<student>L); //输出list类函数
bool cmp(student a, student b); //比较函数
int main()
{
cout << "输入:" << endl;
student a[N]; //定义结构体数组
enion(); //对结构体数组初始化并输出并进行排序
cout << "===================我是分隔符====================" << endl;
cout << "排序后:" << endl;
printList(L); //输出排序后的链表
}
void printList(const list<student>L) //输出list类函数;
{
for (list<student>::const_iterator it = L.begin(); it != L.end(); it++)
{
cout << (*it).name << " " << (*it).age << " " << (*it).score << " " << endl;
}
cout << endl;
}
void enion() //入链函数
{
//list <student> L1;
for (int i = 0; i < N; i++)
{
cin >> a[i].name;
cin >> a[i].age;
cin >> a[i].score;
L.push_back(a[i]);
}
cout << "===================我是分隔符====================" << endl;
cout << "原值:" << endl;
printList(L);
L.sort(cmp);
}
bool cmp(student a, student b)
{
if(a.score!=b.score)
return a.score > b.score; //成绩降序排列
else if (a.age != b.age)
{
return a.age > b.age; //年龄降序排列
}
int tmp = strcmp(a.name, b.name);
if (tmp != 0)
return tmp < 0;
}