Reprinted from: http://www.cnblogs.com/cj695/p/3863142.html
The sort function works very well in use and is very simple, and efficiency is not an order of magnitude with bubbling or selection sorting. In this paper, the use of the sort function in vector is divided into the sort function getting started usage and the custom comp comparison function comparison structure the two most basic functions are speaking its usage:
1. Sort entry:
Use sort to include the algorithm header file, the complete code is as follows
#include <iostream>#include<vector>#include<algorithm>//it seems to be no use, but better to add. using namespacestd;intmain () {vector<int>v; V.push_back ( -); V.push_back ( at); V.push_back (Geneva); V.push_back (233); V.push_back (113); Sort (V.begin (), V.end ()); intI=0; for(i=0;i<5; i++) {cout<<v[i]<<Endl; } return 0;}
The results of the operation are as follows:
3
13
23
113
233
Please press any key to continue ...
Can see the result is from small to large sort, but if I need to sort from big to small?
2, rewrite comp from the big to the small sort.
After adding the comp function, the code is as follows:
#include <iostream>#include<vector>#include<algorithm>using namespacestd;BOOLCompConst int&a,Const int&b) { returnA>b;}intmain () {vector<int>v; V.push_back ( -); V.push_back ( at); V.push_back (Geneva); V.push_back (233); V.push_back (113); Sort (V.begin (), V.end (), comp); intI=0; for(i=0;i<5; i++) {cout<<v[i]<<Endl; } return 0;}
Operation Result:
233
113
23
13
3
Please press any key to continue ...
Why is that? Compare the sort function according to the COMP function to determine the size of the loss, the system default A<b return True, so from small to large row, and my comp function is set to A>b when the return to true, then the final result of the order of the corresponding from small to large into a large to small. Simple Bar ~ ~
3. Sort the structure
With the comp function, we can sort any object in any struct, just need to modify the comp function. The code is as follows:
#include <iostream>#include<vector>#include<algorithm>using namespacestd;structss{intb;};BOOLCompConstSS &a,ConstSS &b) { returna.a<B.A;}intmain () {vector<ss>v; SS S1,s2,s3,s4,s5; s1.a=4; s1.b= at; s2.a=1; s2.b=213; S3.A=2; s3.b=231; s4.a=5; s4.b=123; s5.a=3; s5.b=223; V.push_back (S1); V.push_back (S2); V.push_back (S3); V.push_back (S4); V.push_back (S5); Sort (V.begin (), V.end (), comp); intI=0; for(i=0;i<5; i++) {cout<<v[i].a<<" "<<v[i].b<<Endl; } return 0;}
For example, in the SS structure A is the index number, B is the index corresponding to the value, then I want to sort by index, by overwriting the comp function can be achieved.
Results:
1 213
2 231
3 223
4 23
5 123
Please press any key to continue ...
Reprint from the simplest vector sort usage to custom comparison function the sort algorithm for structure sorting after comp