将这些元素按降序排序

Sort these elements in descending order?

本文关键字:降序 排序 元素      更新时间:2023-10-16

用qsort进行试验,它对我来说运行得很好。我在整个程序中使用函数指针和一些我不习惯的其他特性(例如,void指针)。

然而,

我希望元素按降序排列(即与升序相反)。我能做些什么来实现这个目标?

代码如下:

#include <iostream>
#include <cstdlib>  // Required for qsort
#include <cstring>
using std::cout;
using std::endl;
int compare_strs( const void *arg1, const void *arg2 );
int compare_ints( const void* arg1, const void* arg2 );
int main()
{
    char * shrooms[10] = 
    {
        "Matsutake", "Lobster", "Oyster", "King Boletus",
        "Shaggy Mane", "Morel", "Chanterelle", "Calf Brain",
        "Pig's Ear", "Chicken of the Woods"
    };
    int nums[10] = {99, 43, 23, 100, 66, 12, 0, 125, 76, 2};
    // The address of the array, number of elements
    // the size of each element, the function pointer to 
    // compare two of the elements
    qsort( (void *)shrooms, 10, sizeof( char * ), compare_strs ); 
    qsort( (void *)nums, 10, sizeof( int * ), compare_ints ); 
    // Output sorted lists
    for ( int i = 0; i < 10; ++i )
        cout << shrooms[i] << endl;
    for ( int i = 0; i < 10; ++i )
        cout << nums[i] << endl;
    return 0;
}
int compare_ints( const void * arg1, const void * arg2 )
{
    int return_value = 0;
    if ( *(int *)arg1 < *(int *)arg2 )
        return_value = -1;
    else if ( *(int *)arg1 > *(int *)arg2 )
        return_value = 1;
    return return_value;
}
int compare_strs( const void * arg1, const void * arg2 )
{
    return ( _stricmp( *(char **) arg1, *(char **) arg2 ) );
}

程序以升序输出(即从Calf Brain开始),但我试图让它从Shaggy Mane开始(即降序)。

std::sortstd::stringstd::greater结合使用:

std::string shrooms[10] = 
{
    "Matsutake", "Lobster", "Oyster", "King Boletus",
    "Shaggy Mane", "Morel", "Chanterelle", "Calf Brain",
    "Pig's Ear", "Chicken of the Woods"
};
std::sort(shrooms, shrooms+10, std::greater<std::string>);

如果您不想使用std::sort,只需反转比较函数的结果或反转结果。

最好使用std::sort。没有必要玩复杂的qsort。此外,您应该使用std::string来存储字符串,使用std::vector来存储它们!

编辑:有人发表评论说std::sort不会神奇地反转排序逻辑,所以我的回答是:

为什么不呢?std::sort算法也需要一个比较器!返回负的布尔值,就完成了!

反转比较器函数的逻辑。

inline int rcompare_strs( const void *arg1, const void *arg2 )
{
    return -1*compare_strs(arg1, arg2);
}
inline int rcompare_ints( const void* arg1, const void* arg2 )
{
    return -1*compare_ints(arg1, arg2);
}
qsort( (void *)shrooms, 10, sizeof( shrooms[0] ), rcompare_strs ); 
qsort( (void *)nums, 10, sizeof( nums[0] ), rcompare_ints );