標準/拡張機能 | C/C++ | 依存項目 |
---|---|---|
ISO C |
両方 |
#include <stdlib.h>
void qsort(void *base, size_t num, size_t width,
int(*compare)(const void *element1, const void *element2));
qsort() 関数は、num 個のエレメントの配列をソートします。各エレメントのサイズは width バイトです。ここで、配列の最初のエレメントは base によって指し示されます。
ソートされた配列エレメントは、比較関数で戻されるように、 昇順に保管されます。比較関数において「より大」と「より小」のロジックを反転させれば、 逆順のソートを行うこともできます。 2 つのエレメントが等しい場合、ソート後の配列でのそれらのエレメントの順序は不定です。 qsort() 関数は、ソート後のエレメントで配列の内容を上書きします。
C++ の特殊な動作: C++ と C のリンケージ規約には互換性がありません。従って、qsort() 関数は C++ 関数ポインターを受け取ることができません。C++ 関数ポインター を qsort() 関数に渡そうとすると、コンパイラーがそれにエラーのフラグを立てます。C++ qsort() 関数 を使用するには、比較関数を extern "C" と宣言することにより、この関数が C リンケージを持つようにする必要があります。
qsort() 関数は、値を戻しません。
⁄* CELEBQ01
This example sorts the arguments (argv) in ascending sequence, based on
the ASCII value of each character and string, and using the comparison
function compare() supplied in the example.
*⁄
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
⁄* Declaration of compare() as a function *⁄
#ifdef __cplusplus
extern "C" int compare(const void *, const void *);
#else
int compare(const void *, const void *); ⁄* macro is automatically *⁄
#endif ⁄* defined by the C++⁄MVS compiler *⁄
int main (int argc, char *argv[ ])
{
int i;
argv++;
argc--;
qsort((char *)argv, argc, sizeof(char *), compare);
for (i = 0; i < argc; ++i)
printf("%s¥n", argv[i]);
return 0;
}
int compare (const void *arg1, const void *arg2)
{
⁄* Compare all of both strings *⁄
return(strcmp(*(char **)arg1, *(char **)arg2));
}
出力
Does, this, really, sort, the, arguments, correctly?
この場合、出力は次のようになります。
arguments
correctly?
really
sort
the
this
Does