std::sort 排序使用方法

// //alg_std::sort.cpp // #include <vector> #include <algorithm> #include <functional> // For greater<int>( ) #include <iostream> using namespace std; // Return whether first element is greater than the second bool UDgreater ( int elem1, int elem2 ) { return elem1 > elem2; } class Csort { public: // Return whether first element is less than the second bool operator () (int a,int b) const { return a<b; }; }; int main( ) { vector <int> v1; vector <int>::iterator Iter1; int arr[12]; int i; for ( i = 0 ; i <= 5 ; i++ ) { v1.push_back( 2 * i ); arr[i]=2*i; } for ( i = 6 ; i <= 11 ; i++ ) { arr[i]=23-2*i; } int ii; for ( ii = 0 ; ii <= 5 ; ii++ ) { v1.push_back( 2 * ii + 1 ); } cout << "Original vector v1 = ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")" << endl; cout << "Original array arr = ( " ; for ( int n=0;n<12;n++ ) cout << arr[n] << " "; cout << ")" << endl; //std::sort 默认排序方式 sort( v1.begin( ), v1.end( ) ); cout << "Sorted vector v1 = ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")" << endl; //使用自定义函数给数组排序,第三个参数为函数指针UDgreater //第二个参数为数据最大地址的后一位指针&arr[12]; sort( &arr[0], &arr[12],UDgreater); cout << "Resorted (UDgreater) array arr = ( " ; for ( int n=0;n<12;n++ ) cout << arr[n] << " "; cout << ")" << endl; //使用自定义类的 重载operator() 函数给数组排序,第三个参数为【类名()】 sort( &arr[0], &arr[12],Csort()); cout << "Resorted (Csort()) arr = ( " ; for ( int n=0;n<12;n++ ) cout << arr[n] << " "; cout << ")" << endl; //使用<functional>库中 greater<int>( ) 给向量V1排序; sort( v1.begin( ), v1.end( ), greater<int>( ) ); //sort( v1.begin( ), v1.end( ), Csort() ); 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 //sort( v1.begin( ), v1.end( ), UDgreater ); sort( v1.begin( ), v1.end( ),Csort()); cout << "Resorted (UDgreater) vector v1 = ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")" << endl; getchar(); return 0; }

 

你可能感兴趣的:(vector,less,iterator,Class)