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

This question already has an answer here:




Sorting a vector of custom objects

7 answers

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.