gpt4 book ai didi

c++ - 关于将 std::less 和 std::greater 与 std::sort 一起使用的困惑

转载 作者:可可西里 更新时间:2023-11-01 18:16:12 31 4
gpt4 key购买 nike

在 C 中,排序通常如下例所示实现:

#include <stdio.h>

void Sort( int* arr, int n, bool(*cmp)(int,int) )
{
for( int i=0; i<n-1; i++ )
{
for( int j=i+1; j<n; j++ )
{
if( cmp(arr[i], arr[j]) )
swap( arr[i], arr[j] );
}
}
}

int ascending( int a, int b ) { return a > b; } // greater
int descending( int a, int b ) { return a < b; } // less

void main()
{
int arr[10] = { 1,3,5,7,9,2,4,6,8,10 };

// ascending
Sort( arr, 10, ascending );
for( int i=0; i<10; i++ )
printf( "%d ", arr[i] );

printf( "\n" );


// descending
Sort( arr, 10, descending );
for( int i=0; i<10; i++ )
printf( "%d ", arr[i] );

printf( "\n" );
}

所以我写了一些源代码,如下例所示,期望得到相同的结果:

#include <iostream>
#include <algorithm> // for sort
#include <functional> // for less & greater
using namespace std;

bool gt( int a, int b ) { return a > b; } // greater
bool ls( int a, int b ) { return a < b; } // less

void main()
{
int x[10] = { 1,3,5,7,9,2,4,6,8,10 };

// ascending but descending
sort( x, x+10, gt );
for( int i=0; i<10; i++ )
cout << x[i] << " ";

cout << endl;

// descending but ascending
sort( x, x+10, ls );
for( int i=0; i<10; i++ )
cout << x[i] << " ";

cout << endl;


greater<int> g; // a > b
less<int> l; // a < b

// ascending but descending
sort( x, x+10, g );
for( int i=0; i<10; i++ )
cout << x[i] << " ";

cout << endl;

// descending but ascending
sort( x, x+10, l );
for( int i=0; i<10; i++ )
cout << x[i] << " ";

cout << endl;
}

但我的预期并不正确。

为什么 STL 中的排序不像 C 中的排序那样工作?

最佳答案

std::sort默认按升序排序。如果您正在寻找降序,这里是技巧:

int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::vector<int> vec(x, x+10); // construct std::vector object
std::sort(vec.rbegin(),vec.rend()); // sort it in reverse manner

这样,您明确指出 std::sort 应该将您的数组视为其结尾即开头,反之亦然,这会导致您的数组按降序排序。 Here's the full example.


如果您想使用 std::lessstd::greater ,那么它可能看起来像这样:

int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::sort(x, x + 10, std::less<int>()); // for ascending order
std::sort(x, x + 10, std::greater<int>()); // for descending order

第二种解决方案的完整示例是 here .

关于c++ - 关于将 std::less 和 std::greater 与 std::sort 一起使用的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14828476/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com