zoukankan      html  css  js  c++  java
  • c++ sort函数

    sort() 函数包含在 <algorithm>头文件里。

    需要三个参数,起始地址、结束地址、排序方法。

    没有第三个参数,默认从小到大排序:

     1 #include<iostream>
     2 
     3 #include<algorithm>
     4 using namespace std;
     5 int main()
     6 {
     7    int a[10]={9,6,3,8,5,2,7,4,1,0};
     8    for(int i=0;i<10;i++)
     9    cout<<a[i]<<endl;
    10    sort(a,a+10);
    11    for(int i=0;i<10;i++)
    12    cout<<a[i]<<endl;
    13    return 0;
    14 }

    从大到小排序,增加比较函数:

    #include<iostream>
    #include<algorithm>
    using namespace std;
    bool cmp(int a,int b)
    {
         return a>b;
    }
    int main()
    {
         int a[10]={9,6,3,8,5,2,7,4,1,0};
         for(int i=0;i<10;i++)
         cout<<a[i]<<endl;
         sort(a,a+10,cmp)
         for(int i=0;i<10;i++)
            cout<<a[i]<<endl;
         return 0;
    }

    自己定义了一个结构体node:

    1 struct node
    2 {
    3   int a;
    4   int b;
    5   double c;
    6 }

    先按a值升序排列,如果a值相同,再按b值降序排列,如果b还相同,就按c降序排列。就可以写这样一个比较函数:

    1 bool cmp(node x,node y)
    2 {
    3    if(x.a!=y.a) return x.a<y.a;
    4    if(x.b!=y.b) return x.b>y.b;
    5    return x.c>y.c;
    6 }
  • 相关阅读:
    (31)对象的克隆
    (30)批处理文件.bat
    06.v-on的修饰符
    06.v-on参数问题
    06.2修饰符补充
    06.1v-on基础+-.
    03.data数据对象
    02.el挂载点
    02.5v-pre指令
    02.4v-text指令
  • 原文地址:https://www.cnblogs.com/lxc1910/p/8455022.html
Copyright © 2011-2022 走看看