Share via


qsort_s

更新 : 2007 年 11 月

クイック ソートを実行します。この関数は、「CRT のセキュリティ強化」に説明されているように、qsort のセキュリティが強化されたバージョンです。

void qsort_s(
   void *base,
   size_t num,
   size_t width,
   int (__cdecl *compare )(void *, const void *, const void *),
   void * context
);

パラメータ

  • base
    並べ替える配列の先頭。

  • num
    配列の要素数。

  • width
    配列の要素のサイズ (バイト数)。

  • compare
    比較関数。最初の引数は context ポインタです。2 番目の引数は、検索用の key へのポインタです。3 番目の引数は、key と比較される配列要素へのポインタです。

  • context
    コンテキストへのポインタ。コンテキストは、compare ルーチンがアクセスする必要があるどのオブジェクトでもかまいません。

解説

qsort_s 関数は、width に指定したバイト数の要素 num 個から成る配列を並べ替えるためのクイック ソート アルゴリズムを実装します。base 引数は、並べ替える配列のベースへのポインタです。qsort_s 関数は、並べ替えた後の要素で、この配列を上書きします。引数 compare は、2 つの配列要素を比較し、両者の関係を示す値を返すユーザー指定ルーチンへのポインタです。qsort_s 関数は、並べ替えの間に次の compare ルーチンを 1 回または複数回呼び出し、そのたびに 2 つの配列要素へのポインタを渡します。

compare( context, (void *) & elem1, (void *) & elem2 );

このルーチンは、要素を比較し、次のいずれかの値を返します。

戻り値

説明

< 0

elem1 string1 は string2 より小さいelem2

0

elem1 は elem2 に等しい

> 0

elem1 string1 は string2 より大きいelem2

配列は、比較関数による定義に従って、昇順で並べ替えられます。配列を降順で並べ替えるには、比較関数の "より大きい" と "より小さい" の意味を入れ替えます。

この関数に無効なパラメータが渡されると、「パラメータの検証」に説明されているように、無効なパラメータ ハンドラが呼び出されます。実行の継続が許可された場合、関数から制御が戻り、errno が EINVAL に設定されます。詳細については、「errno、_doserrno、_sys_errlist、および _sys_nerr」を参照してください。

エラー条件

key

base

compare

num

width

errno

NULL

any

any

any

any

EINVAL

any

NULL

any

!= 0

any

EINVAL

any

any

any

any

<= 0

EINVAL

any

any

NULL

any

any

EINVAL

qsort_sは context パラメータを持ち errno を設定すること以外は qsort と同じです。context パラメータを渡すことにより、比較関数はオブジェクト ポインタを使用して、オブジェクト機能や、要素ポインタではアクセスできない他の情報にアクセスできます。context パラメータの追加により、qsort_s 関数のセキュリティが強化されます。これは、context を使用することで、compare 関数に対してデータを利用可能にする静的変数の使用に関連したバグの再入を回避できるためです。

必要条件

ルーチン

必須ヘッダー

qsort_s

<stdlib.h> および <search.h>

互換性の詳細については、「C ランタイム ライブラリ」の「互換性」を参照してください。

ライブラリ :C ランタイム ライブラリ のすべてのバージョン。

使用例

qsort_s 関数の context パラメータの使用方法を次の例に示します。context パラメータにより、スレッド セーフのソートをより簡単に実行できるようになります。スレッド セーフのために同期をとる必要のある静的変数を使用するのではなく、ソートごとに異なる context パラメータを渡します。次の例では、context パラメータとしてローカル オブジェクトが使用されています。

// crt_qsort_s.cpp
// compile with: /EHsc /MT
#include <stdlib.h>
#include <stdio.h>
#include <search.h>
#include <process.h>
#include <locale.h>
#include <locale>
#include <windows.h>
using namespace std;

// The sort order is dependent on the code page.  Use 'chcp' at the
// command line to change the codepage.  When executing this application,
// the command prompt codepage must match the codepage used here:

#define CODEPAGE_850

#ifdef CODEPAGE_850
// Codepage 850 is the OEM codepage used by the command line,
// so \x00e1 is the German Sharp S in that codepage and \x00a4
// is the n tilde.

char *array1[] = { "wei\x00e1", "weis", "annehmen", "weizen", "Zeit",
                   "weit" };
char *array2[] = { "Espa\x00a4ol", "Espa\x00a4" "a", "espantado" };
char *array3[] = { "table", "tableux", "tablet" };

#define GERMAN_LOCALE "German_Germany.850"
#define SPANISH_LOCALE "Spanish_Spain.850"
#define ENGLISH_LOCALE "English_US.850"

#endif

#ifdef CODEPAGE_1252
   // If using codepage 1252 (ISO 8859-1, Latin-1), use \x00df
   // for the German Sharp S and \x001f for the n tilde.
char *array1[] = { "wei\x00df", "weis", "annehmen", "weizen", "Zeit",
                   "weit" };
char *array2[] = { "Espa\x00f1ol", "Espa\x00f1" "a", "espantado" };
char *array3[] = { "table", "tableux", "tablet" };

#define GERMAN_LOCALE "German_Germany.1252"
#define SPANISH_LOCALE "Spanish_Spain.1252"
#define ENGLISH_LOCALE "English_US.1252"

#endif

// The context parameter lets you create a more generic compare.
// Without this parameter, you would have stored the locale in a
// static variable, thus making sort_array vulnerable to thread
// conflicts.

int compare( void *pvlocale, const void *str1, const void *str2)
{
    char s1[256];
    char s2[256];
    strcpy_s(s1, 256, *(char**)str1);
    strcpy_s(s2, 256, *(char**)str2);
    _strlwr_s( s1, sizeof(s1) );
    _strlwr_s( s2, sizeof(s2) );

    locale& loc = *( reinterpret_cast< locale * > ( pvlocale));

    return use_facet< collate<char> >(loc).compare(s1, 
       &s1[strlen(s1)], s2, &s2[strlen(s2)]);

}

void sort_array(char *array[], int num, locale &loc)
{
    qsort_s(array, num, sizeof(char*), compare, &loc);
}

void print_array(char *a[], int c)
{
   for (int i = 0; i < c; i++)
     printf("%s ", a[i]);
   printf("\n");
       
}

void sort_german(void * Dummy)
{
   sort_array(array1, 6, locale(GERMAN_LOCALE));
}

void sort_spanish(void * Dummy)
{   
   sort_array(array2, 3, locale(SPANISH_LOCALE));     
}

void sort_english(void * Dummy)
{   
   sort_array(array3, 3, locale(ENGLISH_LOCALE));   
}

int main( )
{

   int i;
   HANDLE threads[3];
   
   printf("Unsorted input:\n");
   print_array(array1, 6);
   print_array(array2, 3);
   print_array(array3, 3);


   // Create several threads that perform sorts in different
   // languages at the same time. 

   threads[0] = reinterpret_cast<HANDLE>(
                 _beginthread( sort_german , 0, NULL));
   threads[1] = reinterpret_cast<HANDLE>(
                 _beginthread( sort_spanish, 0, NULL));
   threads[2] = reinterpret_cast<HANDLE>(
                 _beginthread( sort_english, 0, NULL));

   for (i = 0; i < 3; i++)
   {
      if (threads[i] == reinterpret_cast<HANDLE>(-1))
      {
         printf("Error creating threads.\n");
         exit(1);
      }
   }

   // Wait until all threads have terminated.
   WaitForMultipleObjects(3, threads, true, INFINITE);
  
   printf("Sorted output: \n");

   print_array(array1, 6);
   print_array(array2, 3);
   print_array(array3, 3);

  
  
}

出力例

Unsorted input:
weiß weis annehmen weizen Zeit weit 
Español España espantado 
table tableux tablet 
Sorted output: 
annehmen weiß weis weit weizen Zeit 
España Español espantado 
table tablet tableux

.NET Framework の相当するアイテム

Sort

参照

参照

検索と並べ替え

bsearch_s

_lsearch_s

qsort