簡體   English   中英

將這些元素按降序排序?

[英]Sort these elements in descending order?

試用qsort,它對我來說運行非常完美。 我在整個程序中使用函數指針以及一些我不習慣的功能(例如,無效指針)。

但是,我希望元素以降序排列(即與升序相反)。 我該怎么做?

這是代碼:

#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 ) );
}

該程序以升序輸出(即從小腿大腦開始),但我試圖讓它從毛茸茸的鬃毛(即降序)開始。 任何幫助將非常感激。

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的commenet不會神奇地逆轉排序邏輯,所以這是我的回復:

那么為何不? 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 ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM