Need to import header file using <algorithm>
#include<algorithm>
Syntax Description: sort (begin, end, cmp), cmp argument can not, if there is no default non-descending order.
I. The basic data type int sort used Case
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { int a[5]={1,3,4,2,5}; sort(a,a+5); for(int i=0;i<5;i++) cout<<a[i]<<' '; return 0; }
Because there is no cmp parameter, the default non-descending order, the result is:
1 2 3 4 5
If the design is non-ascending order, then the function cmp prepared:
bool cmp(int a,int b)
{
return a>b;
}
In fact, for such a simple task (type support "<", ">" comparison operators, etc.), absolutely no need to write out a class. Standard Library has a ready-made, in functional inside, include came on the line. functional provides a bunch of template-based comparison function object. They are (see the name to know the meaning): equal_to <Type>, not_equal_to <Type>, greater <Type>, greater_equal <Type>, less <Type>, less_equal <Type>. For this problem is, greater and less sufficient, to take over the direct use:
升序:sort(begin,end,less<data-type>());
降序:sort(begin,end,greater<data-type>()).
int main ( ) { 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; }
II. Reference data type of string
Among a string of characters Sort:
Can be accomplished using an iterator sequential ordering
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { string str("hello world"); sort(str.begin(),str.end()); cout<<str; return 0; }
Results: Space dehllloorw
Use a reverse iterator can complete the reverse order
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { string str("hello world"); sort(str.rbegin(),str.rend()); cout<<str; return 0; }
The results: wroolllhde space
Comparison between the sort of string
#include<iostream> #include<cstring > #include<algorithm> using namespace std; int main() { string a[4]; for(int i=0;i<4;i++) getline(cin,a[i]); sort(a,a+4); for(int i=0;i<4;i++) cout<<a[i]<<endl; return 0; }
III. In an example of the structure of the two sorting
#include<iostream> #include<algorithm> #include<cstring> using namespace std; struct link { int a,b; }; bool cmp(link x,link y) { if(x.a==y.a) return x.b>y.b; return x.a>y.a; } int main() { link x[4]; for(int i=0;i<4;i++) cin>>x[i].a>>x[i].b; sort(x,x+4,cmp); for(int i=0;i<4;i++) cout<<x[i].a<<' '<<x[i].b<<endl; return 0; }