C + + STL provides a very powerful sorting function sort, which can sort any array, struct, and class, let's take a look at the simplest array sort. The default ascending order, we can also add less or greater to tell the compiler what sort order we want.
vector<int> v = {2015927}; // Ascending order sort (V.begin (), V.end ()), Sort (V.begin (), V.end (),less <int>()); // descending order sort (V.rbegin (), V.rend ()), Sort (V.begin (), v.end (), Greater<int> ());
If it's a two-dimensional array, or sort, we can choose to sort by a column, and if we don't rewrite the CMP function, the default is to sort by the first column, and of course we can sort by the other columns by overriding them:
/*Input MATRIXM = [1 4 2 0 8 3 3 5 1]*///ascending order by first columnsort (M.begin (), M.end ());/*m = [0 8 3 1 4 2 3 5 1]*///descending order by first columnsort (M.rbegin (), M.rend ());/*m = [3 5 1 1 4 2 0 8 3]*///ascending order by second columnSort (M.begin (), M.end (), [] (Constvector<int> &a,Constvector<int> &b) {returna[1] < b[1]; } );BOOLcmpConstvector<int> &a,Constvector<int> &b) {returna[0] > b[0];} Sort (M.begin (), M.end (), CMP);/*m = [1 4 2 3 5 1 0 8 3]*///descending order by second columnSort (M.begin (), M.end (), [] (Constvector<int> &a,Constvector<int> &b) {returna[1] > b[1]; } );BOOLcmpConstvector<int> &a,Constvector<int> &b) {returna[0] < b[0];} Sort (M.begin (), M.end (), CMP);/*m = [0 8 3 3 5 1 1 4 2]*/
C + + sort vector<vector<int> > Container sorting