Or login with:
#include <algorithm> template < class BidirectionalIterator > void stable_sort( BidirectionalIterator first, BidirectionalIterator last ); template < class BidirectionalIterator, class BinaryPredicate > void stable_sort( BidirectionalIterator first, BidirectionalIterator last, BinaryPredicate comp );Parameters:
| Parameter | Description |
|---|---|
| first | A bidirectional iterator addressing the position of the first element in the range to be sorted |
| last | A bidirectional iterator addressing the position one past the final element in the range to be sorted |
| comp | User-defined predicate function object that defines the comparison criterion to be satisfied by successive elements in the ordering. A binary predicate takes two arguments and returns true when satisfied and false when not satisfied |
operator<, and the second compares objects using a function object comp.N is last - first, and best case (if a large enough auxiliary memory buffer is available) is N (log N).#include <vector> #include <algorithm> #include <functional> #include <iostream> using namespace std; // Return if first element is greater than the second bool UDgreater (int elem1, int elem2 ) { return elem1 > elem2; } int main() { vector <int> v1; vector <int>::iterator Iter1; int i; for (i = 0; i <= 5; i++) { v1.push_back( 2*i ); } for (i = 0; i <= 5; i++) { v1.push_back( 2*i ); } cout <<"Original vector v1 = ( " ; for (Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout <<*Iter1<<" "; cout <<")"<<endl; stable_sort(v1.begin( ), v1.end( ) ); cout <<"Sorted vector v1 = ( " ; for (Iter1 = v1.begin( ); Iter1 != v1.end( ); Iter1++) cout <<*Iter1<<" "; cout <<")"<<endl; // To sort in descending order, specify binary predicate stable_sort(v1.begin( ), v1.end( ), greater<int>( ) ); cout <<"Resorted (greater) vector v1 = ( " ; for (Iter1 = v1.begin( ); Iter1 != v1.end( ); Iter1++) cout <<*Iter1<<" "; cout <<")"<<endl; // A user-defined (UD) binary predicate can also be used stable_sort(v1.begin( ), v1.end( ), UDgreater ); cout <<"Resorted (UDgreater) vector v1 = ( " ; for (Iter1 = v1.begin( ); Iter1 != v1.end( ); Iter1++) cout <<*Iter1<<" "; cout <<")"<<endl; return 0; }
You must login to leave a messge