Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort an vector based on any column value by passing the column index as input?

I have already tried the below code but i want to use this same function for sorting based on different columns.

This given code is sorting based on first column only.

bool sortcol( const vector <int> v1, const vector <int> v2)
{
return v1[0]<v2[0];
}

sort(ArrOfTimings.begin(), ArrOfTimings.end(), sortcol);

Is there any way possible to not make multiple functions but making it all work with one only.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Something like this

bool sortcol(int ind, const vector <int> v1, const vector <int> v2)
{
return v1[ind]<v2[ind];
}

sort(ArrOfTimings.begin(), ArrOfTimings.end(), sortcol(0));

>Solution :

You cannot pass additional info to a free function used for comparison for std::sort by means other than global data.

You can create a struct with a member variable storing the column to compare in addition to providing a call operator for comparing the values though.

I’d prefer a lambda, since it results in shorter code though: Simply capture the index.

Note: It’s also beneficial to avoid copying the vector by using references as parameters.

void SortByColumn(std::vector<std::vector<int>> & data, size_t column)
{
    std::sort(data.begin(), data.end(),
              [column](std::vector<int> const& v1, std::vector<int> const& v2)
              {
                  return v1[column] < v2[column];
              });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading