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

1

Below is an example of the application of the qsort function, using a compare function:

#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];

}
  • What is the function compare ?
  • What are the void arguments of this function?
  • How useful are these arguments?
  • asked by anonymous 10.05.2017 / 01:40

    1 answer

    1

    qsort in C and C ++, you want to handle generic type arrays. For this you need:

    • dealing with generic types - for this deals with the address of the the value in question (hence the use of "generic pointers" conventionally designated by "pointer to void" - void * v )
    • know how to copy elements (hence the sizeof(int) parameter)
    • You need to know if a pair of elements is in the right order (hence the comparison function)

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

    • Increasing / Decreasing
    • alphabetic / numeric
    • ignore-case or not
    • Ignoring spaces
    • "version" - sorting
    • in dictionary mode
    • have local accounts, ("ç"="c", ..., or not)

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

        
    10.05.2017 / 10:01