65,186
社区成员




#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int comp(const void *a,const void *b)
{
return *((int*)a)>=*((int*)b);
}
int main()
{
int a[7];
for(int x=0;x<7;x++)
cin>>a[x];
qsort(a,7,sizeof(int),comp);
qsort(a,7,sizeof(int),comp);
for(int x=0;x<7;x++)
cout<<a[x]<<" ";
return 0;
}
For one example of use, see the example under bsearch(3).
Another example is the following program, which sorts the strings given in its command-line arguments:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int
cmpstringp(const void *p1, const void *p2)
{
/* The actual arguments to this function are "pointers to
pointers to char", but strcmp(3) arguments are "pointers
to char", hence the following cast plus dereference */
return strcmp(* (char * const *) p1, * (char * const *) p2);
}
int
main(int argc, char *argv[])
{
int j;
if (argc < 2) {
fprintf(stderr, "Usage: %s <string>...\n", argv[0]);
exit(EXIT_FAILURE);
}
qsort(&argv[1], argc - 1, sizeof(char *), cmpstringp);
for (j = 1; j < argc; j++)
puts(argv[j]);
exit(EXIT_SUCCESS);
}