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 将两个元素视为等价,则它们的顺序是未指定的。

如果数组元素的类型不是 PODType (C++11 前) TriviallyCopyable 类型 (C++11 起) ,则行为未定义。

目录

参数

ptr - 指向待排序数组的指针
count - 数组中元素的数量
size - 数组中每个元素的字节大小
comp - 比较函数,当第一个参数 小于 第二个参数时返回负整数值,当第一个参数 大于 第二个参数时返回正整数值,当参数相等时返回零。

比较函数的签名应等价于以下形式:

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

该函数不得修改传递给它的对象,并且在为相同对象调用时必须返回一致的结果,无论这些对象在数组中的位置如何。

返回值

(无)

注释

尽管名称如此,C++、C 和 POSIX 标准并不要求此函数必须通过 快速排序 实现,也未对其时间复杂性或稳定性作出任何保证。

C++标准库提供的两个重载之所以不同,是因为参数 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++ 标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 405 C++98 数组元素可以是任意类型 限制为 PODType

参阅

在数组中搜索未指定类型的元素
(函数)
将范围按升序排序
(函数模板)
(C++11) (deprecated in C++26)
检查类型是否为平凡类型
(类模板)
C 文档 关于 qsort