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

    用法

    1、sort函数可以三个参数也可以两个参数,必须的头文件#include < algorithm>和using namespace std;

    2、它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n)

    3、Sort函数有三个参数:(第三个参数可不写)

    (1)第一个是要排序的数组的起始地址。

    (2)第二个是结束的地址(最后一位要排序的地址)

    (3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序

    2个参数排序

    sort(v.begin(), v.end());

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

    自定义fun排序

    i>j 降序;

    i<j 升序;

     1 #include <iostream>
     2 #include <algorithm>
     3 using namespace std;
     4 bool sfun(int i, int j){
     5     return i > j;
     6 }
     7 int main()
     8 {
     9     int a[20] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 }, i;
    10     for (i = 0; i<20; i++)
    11         cout << a[i] << endl;
    12     sort(a, a + 20, sfun);
    13     for (i = 0; i<20; i++)
    14         cout << a[i] << endl;
    15     system("pause");
    16     return 0;
    17 }

    结构体排序;

    //需要用static
    //2. sort中的比较函数compare要声明为静态成员函数或全局函数,不能作为普通成员函数,否则会报错。 invalid use of non-static member function
    //因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。

    静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。

    /**
     * Definition for an interval.
     * struct Interval {
     *     int start;
     *     int end;
     *     Interval() : start(0), end(0) {}
     *     Interval(int s, int e) : start(s), end(e) {}
     * };
     */
    class Solution {
    public:
        static bool sfun(Interval a,Interval b){ 
    
            return a.start<b.start;
        }
        void test (vector<Interval>& intervals) {
    
            sort(intervals.begin(),intervals.end(),sfun);
        }
    };
  • 相关阅读:
    开启sftp服务日志并限制sftp访问目录
    Django-16-安装前端项目
    sql
    Django-15-用户模块、认证授权、session会话认证和token认证
    Django-14-项目工程搭建
    开发小技巧
    Django-13-类视图设计原则
    Django-11-自动生成routers路由、自定义action
    Django-9-序列化器中各种校验方式
    Django—问题—生成迁移脚本时报错:You are trying to add a non-nullable field 'gender' to interfaces without a default
  • 原文地址:https://www.cnblogs.com/zle1992/p/10173278.html
Copyright © 2011-2022 走看看