使用 qsort() 函数

发布于 2024-10-02 06:22:21 字数 1167 浏览 2 评论 0原文

我是一名学生&我在一本书上查到了这个函数。它按其应有的方式工作,但我不太了解传递给 qsort() 函数的 sortFunction() 的内部工作原理。如果有人可以详细解释一下,请这样做。提前致谢。

#include<iostream>
#include<stdlib.h>

using namespace std;

//form of sort function required by qsort()
int sortFunction(const void *intOne,const void *intTwo);

const int tableSize = 10;

int main()
{
    int i, table[tableSize];

    //fill the table with values
    for(i = 0; i < tableSize; i++)
    {
        cout << "Enter value " << (i + 1) << " : ";
        cin >> table[i];
    }
    cout << "\n";

    //sort values
    qsort((void*)table, tableSize, sizeof(table[0]), sortFunction);

    //print the results
    for(i = 0; i < tableSize; i++)
    {
        cout << "Value " << (i + 1) << " : " << table[i] << endl;
    }

    cout << "\nDone\n";

    return 0;
}

int sortFunction(const void *a, const void *b)
{
    int intOne = *((int*)a);
    int intTwo = *((int*)b);

    if (intOne < intTwo)
    {
        return -1;
    }
    if (intOne == intTwo)
    {
        return 0;
    }

    return 1;    
}

I'm a student & i looked up this function in a book. It works as it should but i don't quite understand the inner workings of the sortFunction() which is passed to the qsort() function. If some one could explain it in detail, please do. Thanks in advance.

#include<iostream>
#include<stdlib.h>

using namespace std;

//form of sort function required by qsort()
int sortFunction(const void *intOne,const void *intTwo);

const int tableSize = 10;

int main()
{
    int i, table[tableSize];

    //fill the table with values
    for(i = 0; i < tableSize; i++)
    {
        cout << "Enter value " << (i + 1) << " : ";
        cin >> table[i];
    }
    cout << "\n";

    //sort values
    qsort((void*)table, tableSize, sizeof(table[0]), sortFunction);

    //print the results
    for(i = 0; i < tableSize; i++)
    {
        cout << "Value " << (i + 1) << " : " << table[i] << endl;
    }

    cout << "\nDone\n";

    return 0;
}

int sortFunction(const void *a, const void *b)
{
    int intOne = *((int*)a);
    int intTwo = *((int*)b);

    if (intOne < intTwo)
    {
        return -1;
    }
    if (intOne == intTwo)
    {
        return 0;
    }

    return 1;    
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

执手闯天涯 2024-10-09 06:22:21

如果您查看对 qsort 的实际调用...

qsort((void*)table, tableSize, sizeof table[0], sortFunction); 

...您会看到它提供:

  • 一个 void* 地址和整个的大小(以字节为单位)要排序的数据数组,然后
  • 是该数组中一个数据元素的大小,然后
  • 是指向比较函数“sortFunction”的指针。

没有传递任何参数让 qsort 知道元素的类型 - 即如何使用任何单个数据元素中的各个位来表示某些数据值 - 所以qsort 无法有意义地比较两个这样的元素。当您提供...

int sortFunction(const void *a, const void *b)   
{   
    int intOne = *((int*)a);   
    int intTwo = *((int*)b);   

...并且 qsort 调用它时,您将获得两个指针 - 它们指向内存地址,但是当 qsort 调用 sortFunction< /code> 这些 void 指针仍然无法告诉您有关数据元素类型的任何信息,因为 qsort 本身没有任何可传递的洞察力。上面的最后两行代码是您(协调 qsort 调用的程序员)重新应用您一直以来所掌握的有关数据元素类型的知识:在本例中,它们是 < code>ints,因此您将每个 void* 转换为 int* (使用 (int*)a),然后取消引用该 int* 以获取内存地址 a 处的 int。对于b 也是如此。这样,您就恢复了原来存在的两个数字。作为数字。然后,sortFunction 的作用是指示排序完成后应如何对它们进行排序。为了指示 a 应该排在第一位,sortFunction 可以返回任何负值(例如 -1);如果它们相等,则返回 0;,如果 b 应该是第一个,则返回任何正值(例如 1)。 qsort() 接收该信息并使用它来计算出如何在排序时对数据元素进行打乱。

FWIW,C 可以让您更简洁地表达为...

return intOne < intTwo ? -1 :
       intOne == intTwo ? 0 :
       1;

...或(更快,但依赖于布尔比较结果为 0 和 1,这可能会让一些阅读您代码的程序员感到困惑)... ...

return (intOne > intTwo) - (intOne < intTwo);

或者,如果您确定以下内容在数学上永远不会小于INT_MIN(此类值不恰当地环绕为一个大的正数)...

return intOne - intTwo;

If you look at the actual call to qsort...

qsort((void*)table, tableSize, sizeof table[0], sortFunction); 

...you'll see it provides:

  • a void* address and the size (in bytes) of the entire data array to be sorted, then
  • the size of one data element in that array, then
  • a pointer to the comparison function "sortFunction".

There's no argument passed that allows qsort to know what the type of the element is - i.e. how the individual bits in any single data element are used to represent some data value - so there's no way qsort can meaningfully compare two such elements. When you supply...

int sortFunction(const void *a, const void *b)   
{   
    int intOne = *((int*)a);   
    int intTwo = *((int*)b);   

...and qsort calls it, you're getting two pointers - they're to memory addresses but when qsort calls sortFunction those void pointers still tell you nothing about the data element type, as qsort has no insight itself to pass along. The last two lines of code above are where you - the programmer coordinating the qsort call - reapply the knowledge you've had all along about what the data element type is: in this case, they're ints, so you cast each void* to an int* (using (int*)a), then dereference that int* to get the int at memory address a. Similarly for b. In doing so, you've recovered the two numbers that were there as numbers. Then, the job of sortFunction is to indicate how they should be ordered when sorting finishes. To indicate that a should be first, sortFunction can return any negative value (e.g. -1); if they're equivalent, return 0;, and if b should be first, return any positive value (e.g. 1). qsort() receives that information and uses it to work out how to shuffle the data elements around as it sorts.

FWIW, C lets you express that a bit more succinctly as...

return intOne < intTwo ? -1 :
       intOne == intTwo ? 0 :
       1;

...or (faster, but relying on boolean comparison results being 0 and 1, which may confuse some programmers reading your code)...

return (intOne > intTwo) - (intOne < intTwo);

...or, if you're sure the following can never be mathematically less than INT_MIN (such values wrap around to a big positive number inappropriately)...

return intOne - intTwo;
清风不识月 2024-10-09 06:22:21

sortFunction 实际上并不进行排序,它被用作比较函数来确定排序列表中一个元素是否应该在另一个元素之前。

sortFunction isn't actually doing the sorting, it is being used as a comparison function to determine whether one element should precede another in the sorted list.

人疚 2024-10-09 06:22:21

您所谓的“sortFunction”通常称为比较器。它基本上告诉 qsort() 中的通用排序代码正在排序的数组中的两个元素是否比较相等 (0),或者第一个参数是否在第二个 (<0) 或第一个参数之前排序在第二个之后排序 (>0)。

有了这些信息,再加上每行的大小、数组中的行数和数组的开头,qsort() 函数就可以正确地对数据进行排序。

What you called 'sortFunction' is normally called a comparator. It basically tells the generic sort code in qsort() whether two elements in the array being sorted compare equal (0), or whether the first argument sorts before the second (<0) or the first argument sorts after the second (>0).

With that information, plus the size of each row, plus the number of rows in the array and the start of the array, the qsort() function can order the data correctly.

月亮是我掰弯的 2024-10-09 06:22:21

正如您在文档中看到的,qsort函数采用比较器作为它的最后一个参数。该函数用于实际比较参数(告诉哪个参数应该在排序数组中排在第一位)。

As you can see in documentation, qsort function takes a comparator as it's last parameter. This function is used to actually compare parameters (tell which one should go first in a sorted array).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文