What is the purpose of the C++ qsort function compare function?

Asked

Viewed 319 times

1

See below an example of application of the function qsort, using a function compare:

#include <iostream>
#include <cstdlib>
#include <climits>

using namespace std;


int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );

}

int main()
{
    int vet[]={3,2,1};
    qsort(vet,3,sizeof(int),compare);
    for(int i=0;i<3;i++)
    cout<<endl<<vet[i];

}
  1. What is the function for compare?
  2. What are the arguments void of this function?
  3. What is the use of these arguments?
  • Related: https://answall.com/q/199670/5878 (from what I understand, basically the difference between qsort and std::sort is that the first works with a comparison function returning int and the second returning bool). The implementations of the two can also differentiate. I’m not sure, I just thought it might be a nice question for you to analyze until you answer this.

  • In fact, std::sort also accept function/Both for comparison: std::sort(arr.begin(), arr.end(), [](int a, int b) {return a > b; });. qsort should be avoided, because in addition to generally slower, it is not type-safe and does not work with STL.

1 answer

1


qsort in C and C++, intended to handle generic-type arrays. For that you need:

  • handle generic types -- to handle the address of value involved (hence the use of "generic pointers" conventionally designated by "pointer to void" -- void * v )
  • know how to copy elements (hence the parameter sizeof(int))
  • needs to know if a pair of elements is in the right order (hence the comparison function)

For each type we may want to sort in different ways. Consider only the case of strings (see for example the command options sort of Unix...) -- we can order:

  • crescent / decreasing
  • alphabetic / numeric
  • ignore-case or not
  • ignoring spaces
  • "version" - Sorting
  • in dictionary mode
  • have local account, ("ç" = "c", ..., or not )

In your example you passed a function that compares a pair of pointers to whole.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.