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];
}
- What is the function for
compare
? - What are the arguments
void
of this function? - What is the use of these arguments?
Related: https://answall.com/q/199670/5878 (from what I understand, basically the difference between
qsort
andstd::sort
is that the first works with a comparison function returningint
and the second returningbool
). 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.– Woss
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.– Ossetian_Odin