将这些元素按降序排序
Sort these elements in descending order?
用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::sort
与std::string
和std::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 );
相关文章:
- 我正在尝试按降序对地图进行排序,但没有得到预期的结果?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 如何按矩阵行的总和降序对矩阵进行排序 C++.
- 插入按降序排序
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 如何按降序排序?
- 按降序C 排序矢量
- 使用QuickSort算法以降序排序向量
- 偶数升序排序,奇数降序排序
- 按类向量的降序排序
- 按降序排序的最佳方式
- 运算符< std::map 的 int 类型比较的重载?(我希望它按降序排序。
- 使用函数对象按降序排序包含模板用户定义类的stl向量
- 堆排序-使用哪个堆(最小/最大)进行升序排序和降序排序
- 使用Vector对子字符串进行降序排序,但存在分割错误
- 降序排序的最佳方式是什么
- 按降序排序字符串
- Rcpp降序排序
- 将这些元素按降序排序
- 如何对一对向量按降序排序,并按第二个元素排序