C + + sort vector<vector<int> > Container sorting

Source: Internet
Author: User
Tags array sort

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.