Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a vector of vectors in c++ by size of each vector [duplicate]

I have a vector of vectors and i want to sort it by size of each vector ! how could I do that ! I want to use sort function but I can't find any parameter in sort function that determines I want to sort it with size of each content

like image 638
MDK Avatar asked Sep 30 '25 09:09

MDK


1 Answers

You just need to specify a predicate:

vector<vector<int>> vecs;
vecs.push_back(vector<int>(4));
vecs.push_back(vector<int>(2));
vecs.push_back(vector<int>(1));
vecs.push_back(vector<int>(3));

std::sort(vecs.begin(), vecs.end(), [](const vector<int> & a, const vector<int> & b){ return a.size() < b.size(); });

This code sorts the vectors by smallest to largest.

like image 199
dwcanillas Avatar answered Oct 01 '25 23:10

dwcanillas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!