zoukankan      html  css  js  c++  java
  • sort();对结构体数组的排序

    sort(); 位于C++ 

    头文件 #include<algorithm>中

    数组排序(从小到大,从大到小)

    结构体排序(数字参数从大到小...字符串为参数 字典序....)

    代码示例:(直接复制运行对比结果看源码)

    #include<iostream>

    #include<algorithm>

    using namespace std;
    // 对下文所有函数进行声明

    struct node
    {
      int sum;
      char s[10];
    } str[10];


    int cmpn1(node a,node b)
    {
      return a.sum>b.sum;
    }


    int cmpn2(node a,node b)
    {
      return a.s>b.s;
    }


    int cmp(int a,int b)
    {
      return a>b;
    }

    int main()
    {
      int a[100]= {1,3,6,9,4,2,3,6,7,10};
      //一共10个
      cout<<"a数组最初状态 "<<endl;
      for(int i=0; i<10; i++)
        cout<<a[i]<<endl;
      //需要排序首位置加上需排序的位长
      cout<<"默认是从大到小排序 "<<endl;
      sort(a,a+10);
      for(int i=0; i<10; i++)
        cout<<a[i]<<endl;
      cout<<endl;
      cout<<"引入cmp()从大到小 "<<endl;
      sort(a,a+10,cmp);
      for(int i=0; i<10; i++)
        cout<<a[i]<<endl;
      cout<<endl;
      // 结构体赋值
      for(int i=0; i<10; i++)
      {
        str[i].sum=i;
        str[i].s[0]='a'+i;
      }
      cout<<"以sum为参数 调用cmp1进行从大到小 "<<endl;
      sort(str,str+10,cmpn1);
      for(int i=0; i<10; i++)
        cout<<str[i].sum<<endl;
      cout<<endl;
      cout<<"经过sum作为参数排序后,字符串目前状态 "<<endl;
      for(int i=0; i<10; i++)
        cout<<str[i].s<<endl;
      cout<<endl;
      cout<<"以s为参数 调用cmp2进行字典序 "<<endl;
      sort(str,str+10,cmpn2);
      for(int i=0; i<10; i++)
        cout<<str[i].s<<endl;
      cout<<endl;

      return 0;

    }

  • 相关阅读:
    1.MySql安装
    struts文件上传、文件下载
    Java内存模型
    虚拟机类加载机制
    JAVA内存管理
    算法
    POI
    SSH项目(1)
    classpath路径和properties
    AngularJS路由实现单页面跳转
  • 原文地址:https://www.cnblogs.com/maxv/p/10548750.html
Copyright © 2011-2022 走看看