The confusion of using std :: less and std :: more with std :: sort

In C, sorting is usually implemented, as in the following example:

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

So, I wrote some source, as in the following example, expecting the same result:

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

But my expectation was wrong.

Why doesn't sorting in STL work like sorting in C?

+6
source share
2 answers

std::sort behaves this way because it is based on the idea of strict weak ordering , which (usually) is defined in terms of < .

Regarding your question; it currently seems like β€œI wrote a C function that behaves differently with std::sort . Why is it different?”. The answer is: because you wrote another function!

+6
source

std::sort sorts ascending by default. If you are looking for a descending order, here is the trick:

 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 

Thus, you explicitly say that std::sort should process your array, since its end is the beginning and vice versa, which leads to sorting the array in descending order. Here is a complete example.


And if you want to use std::less and std::greater , then it might look like this:

 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 

A complete example with the second solution is here .

+8
source

All Articles