zoukankan      html  css  js  c++  java
  • 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<<"------------------- name id Jd ------------------- "; 47 for (int i=0;i<size;i++) 48 { 49 cout<<" "<<a[i].name<<" "<<a[i].id<<" "<<a[i].Jd<<" "; 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<<" "; 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 }

    运行结果:

  • 相关阅读:
    MongoDB for OPS 02:复制集 RS 配置
    MongoDB for OPS 01:服务介绍与基本使用
    Redis for OPS 07:Redis 补充说明
    Redis for OPS 06:Redis Cluster 集群
    google ctemplate——c++模板引擎
    libctemplate——源码分析
    使用gulp对js、css、img进行合并压缩
    Windows平台交叉编译Arm Linux平台的QT5.7库
    使用gtest对DLL工程进行单元测试的实践
    websocket++简单使用例子
  • 原文地址:https://www.cnblogs.com/-210843013/p/6090659.html
Copyright © 2011-2022 走看看