首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::qsort

Defined in header <cstdlib>

?

?

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

(1)

?

extern "C++" using /*compare-pred*/ = int(const void*, const void*); // exposition-only extern "C" using /*c-compare-pred*/ = int(const void*, const void*); // exposition-only

(2)

?

对指定数组进行排序。ptr按升序排列。数组包含count元素size字节。所指函数comp用于对象比较。

如果comp将两个元素表示为等效元素,它们的顺序未定义。

参数

ptr

-

pointer to the array to sort

count

-

number of elements in the array

size

-

size of each element in the array in bytes

comp

-

comparison function which returns ?a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equal. The signature of the comparison function should be equivalent to the following: int cmp(const void *a, const void *b); The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array. ?

返回值

%280%29

注记

尽管名称,C++、C和POSIX标准不要求使用快速排序或使任何复杂性或稳定性得到保证。

数组元素的类型必须是TrivialType,否则行为就没有定义。

C++标准库提供的两个重载是不同的,因为参数的类型comp分别为%28语言链接是其类型%29的一部分。

下面的代码使用qsort()...

代码:

代码语言:javascript
复制
#include <iostream>
#include <cstdlib>
#include <climits>
 
int main()
{
    int a[] = {-2, 99, 0, -743, 2, INT_MIN, 4};
    constexpr std::size_t size = sizeof a / sizeof *a;
 
    std::qsort(a, size, sizeof *a, [](const void* a, const void* b)
    {
        int arg1 = *static_cast<const int*>(a);
        int arg2 = *static_cast<const int*>(b);
 
        if(arg1 < arg2) return -1;
        if(arg1 > arg2) return 1;
        return 0;
 
    //  return (arg1 > arg2) - (arg1 < arg2); // possible shortcut
    //  return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present)
    });
 
    for(int ai : a)
        std::cout << ai << ' ';
}

二次

产出:

二次

代码语言:javascript
复制
-2147483648 -743 -2 0 2 4 99

二次

另见

bsearch

searches an array for an element of unspecified type (function)

sort

sorts a range into ascending order (function template)

is_trivial (C++11)

checks if a type is trivial (class template)

C.qSort的文档

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com