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 }
  • 相关阅读:
    luoguP5024 保卫王国 动态dp
    luoguP4571 [JSOI2009]瓶子和燃料 裴蜀定理
    luoguP3235 [HNOI2014]江南乐 数论分块 + 博弈论
    luoguP4101 [HEOI2014]人人尽说江南好 结论
    hdu 3032 NIm or not Nim? Multi SG
    luoguP4279 [SHOI2008]小约翰的游戏 Anti-SG 博弈论
    luoguP3480 [POI2009]KAM-Pebbles 阶梯Nim
    Educational Codeforces Round 65 (Div. 2)
    [PKUSC2018]主斗地(搜索+贪心)
    Codeforces Round #557 (Div. 1)
  • 原文地址:https://www.cnblogs.com/program-ai-cv-ml-se-fighting/p/11924550.html
Copyright © 2011-2022 走看看