升序:sort(begin,end,less());降序:sort(begin,end,greater ()).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< < ());for(i=0;i<20;i++)cout< <
使用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#include #include #include using namespace std;bool Comp(const int &a,const int &b){ return a>b;}int main( ){ vector v1; vector ::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 < ()); for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 ; cout<< endl;}