zoukankan      html  css  js  c++  java
  • sort用法

    1、sort(a,a+7) a表示要排序的首地址,数组名代表的就是一个数组的首地址,7是要排序的元素个数

    1     int a[] = { 8,2,9,1,0,5,6 };
    2     sort(a, a + 7);
    3     for (int i = 0; i < 7; i++) {
    4         cout << a[i] << " ";//0 1 2 5 6 8 9
    5     }

    2、sort(a+1,a+5) 表示将[a+1,a+5)区间中的元素排序

    1     int a[] = { 8,2,9,1,0,5,6 };
    2     sort(a+1, a + 5);
    3     for (int i = 0; i < 7; i++) {
    4         cout << a[i] << " ";//8 0 1 2 9 5 6
    5     }

    3、sort(a,a+7,greater<int>()) 按从大到小的顺序排列

      sort默认是按照从小到大的顺序排列的,greater表示更大的意思,即更大的数排在前面,<int>表示要排序的数组中的元素是int类型的

    1     int a[] = { 8,2,9,1,0,5,6 };
    2     sort(a, a + 7,greater<int>());
    3     for (int i = 0; i < 7; i++) {
    4         cout << a[i] << " ";//9 8 6 5 2 1 0
    5     }

    4、定义一个比较大小的函数cmp

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 bool cmp(int x, int y) {
     5     return x > y;//表示大的排在前面
     6 }
     7 int main() {
     8     int a[] = { 8,2,9,1,0,5,6 };
     9     sort(a, a + 7,cmp);
    10     for (int i = 0; i < 7; i++) {
    11         cout << a[i] << " ";//9 8 6 5 2 1 0
    12     }
    13 
    14     return 0;
    15 }

    5、比较结构体大小

    方法一:

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 struct A {
     5     int x;
     6     int y;
     7 };
     8 bool cmp(A m, A n) {
     9     return  m.y> n.y;//y更大的排在前面
    10 }
    11 int main() {
    12     A a[] = { {1,3},{4,1},{5,9},{1,6},{8,2} };
    13     sort(a, a + 5,cmp);
    14     for (int i = 0; i < 5; i++) {
    15         cout << "(" << a[i].x << "," << a[i].y << ")" << " ";
    16         //(5,9) (1,6) (1,3) (8,2) (4,1)
    17     }
    18 
    19     return 0;
    20 }

    方法二:

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 struct A {
     5     int x;
     6     int y;
     7     bool operator<(const A &s)const {
     8         return y > s.y;//y大的在此结构体中定义的‘<’的左边,sort中<左边的在前面
     9     }
    10 };
    11 int main() {
    12     A a[] = { {1,3},{4,1},{5,9},{1,6},{8,2} };
    13     sort(a, a + 5);
    14     for (int i = 0; i < 5; i++) {
    15         cout << "(" << a[i].x << "," << a[i].y << ")" << " ";
    16         //(5,9) (1,6) (1,3) (8,2) (4,1)
    17     }
    18 
    19     return 0;
    20 }
  • 相关阅读:
    python 字典dict
    前端笔记之HTML
    Activity工作流框架入门(二)API使用DEMO
    工作流Activity框架入门(一)
    使用Ecplise git commit时出现"There are no stages files"
    安装Eclipse activity插件 报异常 Cannot complete the install because one or more required items could not be
    JQuery--使用JQuery 的$.ajax 方法进行异步请求,导致页面闪烁
    JQuery--JQuery面向对象编程快速入门-插件开发
    VIM编辑器常用命令
    Git入门
  • 原文地址:https://www.cnblogs.com/program-ai-cv-ml-se-fighting/p/11924550.html
Copyright © 2011-2022 走看看