• sqort函数用法总结


    qsort包含在<stdlib.h>头文件中,此函数根据你给的比较条件进行快速排序,通过指针移动实现排序。排序之后的结果仍然放在原数组中。使用qsort函数必须自己写一个比较函数。

    函数原型:

    void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );

    用法以及参数说明:

    Sorts the num elements of the array pointed by base, each element size bytes long, using the comparator function to determine the order.

    The sorting algorithm used by this function compares pairs of values by calling the specified comparator function with two pointers to elements of the array.

    The function does not return any value, but modifies the content of the array pointed by base reordering its elements to the newly sorted order.

    base Pointer to the first element of the array to be sorted.(数组起始地址)
    num Number of elements in the array pointed by base.(数组元素个数)
    size Size in bytes of each element in the array.(每一个元素的大小)
    comparator Function that compares two elements.(函数指针,指向比较函数)
    1、The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.
    2、The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.
    Return Value none (无返回值)

     

     

    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <string.h>
    using namespace  std;
    
    bool cmp_int(int a, int b)
    {
        return a > b;
    }
    
    bool cmp_string(string a, string b)
    {
    return a > b;
    }
    
    bool cmp_char(char a, char b)
    {
        return a > b;
    }
    
    
    
    int main()
    {
        int num;
        cin >> num;
        int s[1000];
        for (int i = 1; i <=num;i++)
        {
            cin >> s[i];
        }
        sort(s + 1, s + 1 + num,cmp_int);
        for (int i =1; i <=num; i++)
        {
            cout<< s[i]<<" ";
        }
        cout << endl;
        string s1[100];
        for (int i = 1; i <= num; i++)
        {
            cin >> s1[i];
        }
        sort(s1 + 1, s1 + 1 + num, cmp_string);
        for (int i = 1; i <= num; i++)
        {
            cout << s1[i] << " ";
        }
        cout << endl;
        char  s2[1000];
        cin >> s2;
        int len = strlen(s2);
        sort(s2, s2 + len, cmp_char);
        cout << s2 << endl;
        return 0;
    }

     

     

  • 相关阅读:
    RTTI机制
    constexpr
    map/unordered_map
    Centos 安装Oracle
    JS带进度 文件 重复 自动 异步上传
    xadmin 小组件默认折叠
    xadmin datetime 类型报错 unsupported format characte
    Vmware 链接克隆 转 完整克隆 Converting a linked clone virtual machine to a full clone virtual machine
    vsftpd 530 500 553
    百度自然语言处理API调用
  • 原文地址:https://www.cnblogs.com/locojyw/p/3411752.html
Copyright © 2020-2023  润新知