升序:sort(begin,end,less<data-type>()); 降序:sort(begin,end,greater<data-type>()). int _tmain(int argc, _TCHAR* argv[]) { int a[20]={2,4,1,23,5,76,0,43,24,65},i; for(i=0;i<20;i++) cout<<a[i]<<endl; sort(a,a+20,greater<int>()); for(i=0;i<20;i++) cout<<a[i]<<endl; return 0; }
使用sort排序:需要头文件#include<algorithm>,
sort(vec.begin(),vec.end());(默认是按升序排列,即从小到大).
可以通过重写排序比较函数按照降序比较,如下:
定义排序比较函数:
bool Comp(const int &a,const int &b)
{
return a>b;
}
调用时:sort(vec.begin(),vec.end(),Comp),这样就降序排序。
#include <vector> #include <algorithm> #include <iostream> #include<string> using namespace std; bool Comp(const int &a,const int &b) { return a>b; } int main( ) { vector <char> v1; vector <char>::iterator Iter1; int i; string s; cin>>s; for ( i = 0 ; i < s.length() ; i++ ) { v1.push_back( s[i] ); } for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 ; cout <<endl; //reverse (v1.begin( ), v1.end( ) ); sort(v1.begin(),v1.end(),greater<char>()); for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 ; cout<< endl; }