zoukankan      html  css  js  c++  java
  • 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;
    }

     

     

  • 相关阅读:
    记-码农的“启蒙”之《程序设计语言-实践之路》和《面向对象分析和设计》两书
    记-阅读以及书籍推荐(2014年9月7日更新)
    初探领域驱动设计(1)为复杂业务而生
    异步编程 In .NET
    Windows平台分布式架构实践
    Windows平台分布式架构实践
    一不小心写了个WEB服务器
    MVC5
    从Membership 到 .NET4.5 之 ASP.NET Identity
    bootstrap + requireJS+ director+ knockout + web API = 一个时髦的单页程序
  • 原文地址:https://www.cnblogs.com/locojyw/p/3411752.html
Copyright © 2011-2022 走看看