#include<iostream>
#include<algorithm>
using namespace std;
struct student
{
int sno;
char name[20];
};
//qsort比较器
int com(const void *a, const void *b)//qsort基本比较器
{//void指针必须先进行强制类型转换
return *((int *)a) - *((int *)b);
}
int com1(const void *a, const void *b)//student按照姓名排序
{
return strcmp(((student *)a)->name ,((student *)b)->name);
}
//sort比较器
template<typename T>
bool compare(T &a, T &b)//sort基本比较器
{
return a > b;
}
bool compare1(student &a, student &b)//student按照姓名排序
{
return a.name>b.name;
}
void show(student a[], int num)//显示结构体
{
int t=1;
for (int i = 0; i < num; i++)
{
cout << a[i].sno << " " << a[i].name;
cout << endl;
}
}
void showarry(int a[], int num) {//显示数组
for (int i = 0; i < 3; i++)
{
cout << a[i] << " ";
}
}
int main() {
int a[3] = { 2,4,1 };
cout << "基本数组的排序:"<<endl;
cout << "使用qsort排序结果:" << endl;
qsort(a, 3, sizeof(int), com);
showarry(a, 3);
cout << endl;
cout << "使用sort排序结果:" << endl;
sort(a,a + 3, compare<int>);
showarry(a, 3);
cout << endl;
cout <<"结构体排序:"<< endl;
student s[3] = { {1,"jwt"},{2,"byj"}, {3,"abc"} };
cout << "使用qsort排序结果:" << endl;
qsort(s, 3, sizeof(student), com1);
show(s, 3);
cout << "使用sort排序结果:" << endl;
sort(s, s + 3, compare1);
show(s, 3);
system("pause");
return 0;
}
网友评论