Namespaces
Variants

std:: qsort

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
qsort
Numeric operations
Operations on uninitialized memory
ヘッダーで定義 <cstdlib>
void qsort ( void * ptr, std:: size_t count,

std:: size_t size, /* c-compare-pred */ * comp ) ;
void qsort ( void * ptr, std:: size_t count,

std:: size_t size, /* compare-pred */ * comp ) ;
(1)
extern "C" using /* c-compare-pred */ = int ( const void * , const void * ) ;
extern "C++" using /* compare-pred */ = int ( const void * , const void * ) ;
(2) ( 説明専用* )

指定された配列を ptr が指すアドレスから昇順にソートします。配列は count 個の要素を持ち、各要素のサイズは size バイトです。 comp が指す関数はオブジェクト比較に使用されます。

comp が2つの要素を等価と示す場合、それらの順序は未規定です。

配列の要素の型が PODType (C++11まで) TriviallyCopyable (C++11以降) でない場合、動作は未定義です。

目次

パラメータ

ptr - ソート対象の配列へのポインタ
count - 配列の要素数
size - 配列の各要素のサイズ(バイト単位)
comp - 比較関数。第一引数が第二引数より 小さい 場合は負の整数値、第一引数が第二引数より 大きい 場合は正の整数値、引数が等価の場合はゼロを返す。

比較関数のシグネチャは以下と同等であるべき:

int cmp ( const void * a, const void * b ) ;

この関数は渡されたオブジェクトを変更してはならず、配列内の位置に関わらず同じオブジェクトに対して呼び出された場合には一貫した結果を返さなければならない。

戻り値

(なし)

注記

名前にもかかわらず、C++、C、およびPOSIX標準は、この関数が Quicksort を使用して実装されることや、計算量や安定性に関する保証を一切要求していません。

C++標準ライブラリが提供する2つのオーバーロードは、パラメータ comp の型が異なるため区別されます( 言語リンケージ はその型の一部です)。

以下のコードは整数の配列を qsort() を使用してソートします:

#include <array>
#include <climits>
#include <compare>
#include <cstdlib>
#include <iostream>
int main()
{
    std::array a{-2, 99, 0, -743, INT_MAX, 2, INT_MIN, 4};
    std::qsort
    (
        a.data(),
        a.size(),
        sizeof(decltype(a)::value_type),
        [](const void* x, const void* y)
        {
            const int arg1 = *static_cast<const int*>(x);
            const int arg2 = *static_cast<const int*>(y);
            const auto cmp = arg1 <=> arg2;
            if (cmp < 0)
                return -1;
            if (cmp > 0)
                return 1;
            return 0;
        }
    );
    for (int ai : a)
        std::cout << ai << ' ';
    std::cout << '\n';
}

出力:

-2147483648 -743 -2 0 2 4 99 2147483647

欠陥報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 405 C++98 配列の要素は任意の型を持つことができた PODType に限定

関連項目

未指定の型の要素を配列から検索する
(関数)
範囲を昇順にソートする
(関数テンプレート)
(C++11) (C++26で非推奨)
型がトリビアルかどうかをチェックする
(クラステンプレート)