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

Time:06-02

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.

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));

CodePudding user response:

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];
              });
}
  • Related