1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <cstdlib>
#include <iterator>
int main()
{
int arr[] { 11, 24, 17, 21, 14, 12, 10, 19, 23, 22, 13, 20, 16, 15, 18 } ;
for( int v : arr ) std::cout << v << ' ' ;
std::cout << '\n' ;
// callable object called by std::qsort to compare elements being sorted
// its signature must be equivalent to int( const void*, const void* )
// ie. it accepts two arguments of type const void* and returns int
// if it is a pointer to a free function, it may have either C or C++ linkage.
const auto cmp_int = [] ( const void* pa, const void* pb )
{
// the two arguments pa and pb are pointers to the two elements to be compared
// if the comparison function modifies either of the two objects,
// it would engender undefined behaviour.
// we know that we are using this compare function to sort an array of int
// get the values of the integers to be compared (via compile-time casts)
const int a = *static_cast< const int* >(pa) ;
const int b = *static_cast< const int* >(pb) ;
// this compare function must return:
//
// a negative integer value if the element identified by the first argument
// should appear before the element identified by the second argument in the sorted sequence
// (in our case, for sort in ascending order, if a < b )
//
// a positive integer value if the element identified by the first argument
// should appear after the element identified by the second argument in the sorted sequence
// (in our case, for sort in ascending order, if a > b )
//
// zero if the the element identified by the first argument may appear either before
// or after the element identified by the second argument in the sorted sequence
// (in our case, for sort in ascending order, if a == b )
return (a>b) - (b>a) ;
};
std::qsort( std::begin(arr), sizeof(arr)/sizeof(arr[0]), sizeof(int), cmp_int ) ;
for( int v : arr ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
|