• 理解qsort 中的 cmp


    百度了很多的资料都没有明白qsort 中 cmp 的用处,用Bing 一搜就搜到一篇自认为比其他都解析清楚的文章

    直接贴出来算了

    comparPointer to a function that compares two elements.
    This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:

     
    int compar (const void* p1, const void* p2);
     


    Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):

    return valuemeaning
    <0 The element pointed by p1 goes before the element pointed by p2
    0 The element pointed by p1 is equivalent to the element pointed by p2
    >0 The element pointed by p1 goes after the element pointed by p2

    假如你要按升序排列数组,需要处理两个参数P1 ,P2,如果P1 > P2 ,那cmp需要返回的是一个<0的值,所以是P1-P2

    若P1<P2 ,那么cmp需要返回一个 >0的值,所以同样是P1-P2,一点都不矛盾。

    假如你要按降序排列数组,需要处理两个参数P1 ,P2,如果P1 > P2 ,排序应该是P1在P2前面,那cmp需要返回的是一个<0的值,所以是P2-P1 ,若P1<P2 ,那么cmp需要返回一个 >0的值,所以同样是P2-P1

  • 相关阅读:
    引用赋值的问题
    mysql的笔记
    输入法失败
    eclipse的快捷键
    c++/c在两个文件公用一个变量
    用c++ sttring检测名字是否有空格
    QLineEdit的信号函数
    c++博客转载
    qt-博客
    QT聊天室--重大bug
  • 原文地址:https://www.cnblogs.com/been/p/4470199.html
Copyright © 2020-2023  润新知