c – 关于使用std :: sort的std :: less和std :: greater的混淆

前端之家收集整理的这篇文章主要介绍了c – 关于使用std :: sort的std :: less和std :: greater的混淆前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在C中,sort通常实现,如下例所示:
  1. #include <stdio.h>
  2.  
  3. void Sort( int* arr,int n,bool(*cmp)(int,int) )
  4. {
  5. for( int i=0; i<n-1; i++ )
  6. {
  7. for( int j=i+1; j<n; j++ )
  8. {
  9. if( cmp(arr[i],arr[j]) )
  10. swap( arr[i],arr[j] );
  11. }
  12. }
  13. }
  14.  
  15. int ascending( int a,int b ) { return a > b; } // greater
  16. int descending( int a,int b ) { return a < b; } // less
  17.  
  18. void main()
  19. {
  20. int arr[10] = { 1,3,5,7,9,2,4,6,8,10 };
  21.  
  22. // ascending
  23. Sort( arr,10,ascending );
  24. for( int i=0; i<10; i++ )
  25. printf( "%d ",arr[i] );
  26.  
  27. printf( "\n" );
  28.  
  29.  
  30. // descending
  31. Sort( arr,descending );
  32. for( int i=0; i<10; i++ )
  33. printf( "%d ",arr[i] );
  34.  
  35. printf( "\n" );
  36. }

所以我在下面的例子中编写了一些源代码,期望得到相同的结果:

  1. #include <iostream>
  2. #include <algorithm> // for sort
  3. #include <functional> // for less & greater
  4. using namespace std;
  5.  
  6. bool gt( int a,int b ) { return a > b; } // greater
  7. bool ls( int a,int b ) { return a < b; } // less
  8.  
  9. void main()
  10. {
  11. int x[10] = { 1,10 };
  12.  
  13. // ascending but descending
  14. sort( x,x+10,gt );
  15. for( int i=0; i<10; i++ )
  16. cout << x[i] << " ";
  17.  
  18. cout << endl;
  19.  
  20. // descending but ascending
  21. sort( x,ls );
  22. for( int i=0; i<10; i++ )
  23. cout << x[i] << " ";
  24.  
  25. cout << endl;
  26.  
  27.  
  28. greater<int> g; // a > b
  29. less<int> l; // a < b
  30.  
  31. // ascending but descending
  32. sort( x,g );
  33. for( int i=0; i<10; i++ )
  34. cout << x[i] << " ";
  35.  
  36. cout << endl;
  37.  
  38. // descending but ascending
  39. sort( x,l );
  40. for( int i=0; i<10; i++ )
  41. cout << x[i] << " ";
  42.  
  43. cout << endl;
  44. }

但我的期望并不正确.

为什么在STL中排序不像C中的排序?

解决方法

std :: sort的行为与此类似,因为它基于 strict weak ordering的概念,它通常根据<操作符. 至于你的问题;它目前似乎是“我写了一个与std :: sort行为不同的C函数.为什么它不同?”.答案是:因为你写了不同的功能

猜你在找的C&C++相关文章