基于C/C++的标准库之sort排序

本文介绍了使用C++实现的几种排序算法示例,包括基于结构体的学生信息按姓名首字母、ID及绩点排序,以及按整数个位数进行排序的方法。每种排序都定义了特定的比较规则,并通过输出展示了排序效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  sort--01:

 1 #include "iostream"
 2 #include "algorithm"
 3 #include "string.h"
 4 using namespace std;
 5 
 6  // student 结构体
 7 struct Student
 8 {
 9     char name[20];
10     int id;
11     double Jd;
12 
13 };
14 
15  //按首字母排序
16 
17 struct studentrule1 
18 {
19     bool operator() (const Student & s1, const Student &s2)
20     {
21         if(stricmp(s1.name,s2.name)<0)
22             return true;
23     return false;
24     }
25 };
26 // 按id 小到大
27 struct studentrule2
28 {
29     bool operator()(const Student &s1,const Student &s2)
30     {
31         return s1.id<s2.id;
32     }
33 };
34 
35  // 按Jd大到小
36 struct studentrule3
37 {
38     bool operator()(const Student &s1,const Student &s2)
39     {
40         return s1.Jd>s2.Jd ;
41     }
42 };
43  //输出函数
44 void Print(Student a[],int size)
45 {
46         cout<<"-------------------\n  name  id  Jd \n-------------------\n\n\n";
47 for (int i=0;i<size;i++)
48 {
49     cout<<"  "<<a[i].name<<"   "<<a[i].id<<"   "<<a[i].Jd<<"\n";
50 }
51 }
52 
53  // 初始化
54 Student student[]=
55 {
56     {"Aack",110,3.9},{"Cary",109,3.5},
57     {"Bob",108,3.3},{"Zerol",111,3.2},
58     {"Jaeger",112,3.0},{"Dick",107,3.8}
59 
60 };
61 int main()
62 {
63     
64     int n =sizeof(student)/sizeof(Student);
65     sort(student,student+n,studentrule1());
66     Print(student,n);
67     sort(student,student+n,studentrule2());
68     Print(student,n);
69     sort(student,student+n,studentrule3());
70     Print(student,n);
71     system("pause");
72     return 0;
73      
74 }

运行结果:

  // sort--02: 按个位数排序
 1 #include"iostream"
 2 #include "string.h"
 3 #include "algorithm"
 4 using namespace std;
 5 struct MyStruct
 6 {
 7     bool operator()(const int &n1,const int &n2)
 8     {
 9     return n1%10<n2%10;
10     }
11 
12 };
13 
14 void Print(int a[],int size)
15 {
16 for (int i=0;i<size;i++)
17 {
18     cout<<a[i]<<" ";
19 }
20 cout<<"\n";
21 }
22 int main()
23 {
24     int a[]={20,27,79,62,53,101,288,74,56,95};25     int n =sizeof(a)/sizeof(int);
26     sort(a,a+n,MyStruct());
27     Print(a,n);
28     system("pause");
29     return 0;
30 }

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ya土豆儿~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值