c++标准库之sort排序

  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 }

运行结果:

posted @ 2016-11-22 18:46  #ifndef  阅读(5102)  评论(0编辑  收藏  举报