zoukankan      html  css  js  c++  java
  • sort()的部分用法

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>//sort要包含的头文件 
     4 #include <time.h>
     5 using namespace std;
     6 
     7 struct st
     8 {
     9     int x,y;
    10 };
    11 st s[10];
    12 
    13 bool cmp(st a,st b)//自定义的比较函数 
    14 {
    15     if (a.x<b.x)//先按第一位数升序排列 
    16     {
    17         return true;
    18     }
    19 
    20     else if (a.x==b.x)
    21     {
    22         if (a.y<b.y)//再按第二位数升序排列 
    23         {
    24             return true;
    25         }
    26     }
    27 
    28     return false;
    29 }
    30 
    31 int main()
    32 {
    33     srand(time(NULL));
    34     int i;
    35     for (i=0;i<10;i++)//生成随机数产生样例 
    36     {
    37         s[i].x=rand()%10;
    38         s[i].y=rand()%10;
    39     }
    40 
    41     for (i=0;i<10;i++)
    42     {
    43         printf("%d %d
    ",s[i].x,s[i].y);
    44     }
    45 
    46     printf("
    ");
    47     sort(s,s+10,cmp);// sort默认升序排列 
    48 
    49     for (i=0;i<10;i++)
    50     {
    51         printf("%d %d
    ",s[i].x,s[i].y);
    52     }
    53 
    54     return 0;
    55 }

    另外要注意sort()的排序范围:数组a[ ]下标从0开始,sort(a+1,a+5)的范围是a[1]~a[4],是左闭右开区间!!

    给字符串a本排序:sort(a.begin(),a.begin()+a.size());

  • 相关阅读:
    Spring 发生 has not been refreshed yet 异常
    rsyslog config
    grok
    阿里云态势
    Unity的asm笔记
    Unity2020或Unity2019安装后无法启动
    rider代码折叠
    使用rider调试lua
    MacType更好的字体渲染
    Unity字体和画面花屏处理
  • 原文地址:https://www.cnblogs.com/hemeiwolong/p/8994986.html
Copyright © 2011-2022 走看看