Once the header file include # <algorithm> is included, a vector can be sorted directly using the Sort function:
1 //Sort Algorithm Example2#include <iostream>//Std::cout3#include <algorithm>//Std::sort4#include <vector>//std::vector5 6 BOOLMyFunction (intIintj) {return(i<j); } 7 8 structMyClass {9 BOOL operator() (intIintj) {return(i<j);} Ten } MyObject; One A intMain () { - intMyints[] = { +, in, A, $, -, the, -, -}; -std::vector<int> Myvector (myints, myints+8);// All in all the - //using default comparison (operator <): -Std::sort (Myvector.begin (), Myvector.begin () +4);//(a) - + //using function as comp -Std::sort (Myvector.begin () +4, Myvector.end (), myfunction);//(+) + A //using object as Comp atStd::sort (Myvector.begin (), Myvector.end (), MyObject);//(a) - - //Print out content: -Std::cout <<"Myvector contains:"; - for(std::vector<int>::iterator It=myvector.begin (); It!=myvector.end (); ++it) -Std::cout <<' '<< *it; inStd::cout <<'\ n'; - to return 0; +}
But when a variable in a vector is a struct and needs to be sorted by one of the elements of the struct, some modification is required:
1#include"PrivateHeader.h"2#include <string>3#include <vector>4#include <iostream>5#include <algorithm>6 usingSTD::string;7 usingstd::vector;8 usingstd::cout;9 usingStd::endl;Ten using namespacestd; One Atypedefstruct - { - floatscore; the stringfile_name; - stringAll_file_name; - - }tfileprop; + - BOOLGreatersort (Tfileprop A, tfileprop b) + { A return(A.score >b.score); at } - BOOLLesssort (Tfileprop A, tfileprop b) - { - return(A.score <b.score); - } -Vector<tfileprop>Vecfileprop; in -Vecfileprop.push_back (Tfileprop);//push operations on vectors to +Std::sort (Vecfileprop.begin (), Vecfileprop.end (), greatersort);//sort in descending order -Std::sort (Vecfileprop.begin (), Vecfileprop.end (), lesssort);//sort in ascending order
Also, when using Iang to pass a parameter data, because the command line receives the parameters are stored in char** argv, so you need to cast first, after a string as the intermediate conversion variable, and finally into the int type, in addition, I think because it is a char type of reason, It should be possible for the master to pass 0-255 of arguments, but it is not right to think about it, because no matter how large the number is, it is passed in a string, and then the string type is forced to turn to the int type, so there is no size limit of 256.
1 intMainintargcChar**argv)2 {3 //Statistical Time4 //timestatistics ();5 6 //all results are placed in a folder display7 8 intNum_save;9 if(ARGC = =2)Ten { OneSTD::stringThres = argv[1]; ANum_save =atof (Thres.c_str ()); - //std::cout << "(int) argv[1] is" << argv[1]; - //std::cout << "Num_save is" << num_save; the } - Else - { -Num_save = -; + } - Showallresult (num_save); + A at return 1; -}
Reference: http://blog.csdn.net/zhouxun623/article/details/49887555
Structure vector sorting in C + +