按降序对这些元素进行排序?

时间:2013-01-20 05:05:30

标签: c++ pointers qsort

尝试使用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开始(即降序)。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

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,只需反转比较函数的结果或反转结果。

答案 1 :(得分:2)

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

编辑: 有人发布了一个纪念版,std :: sort不会神奇地反转排序逻辑,所以这是我的回复:

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

答案 2 :(得分:1)

反转比较器功能的逻辑。

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 ); 
相关问题