Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ How to sort the rows of a 2d Vector, by the values in each rows column

The Aim: I have a 2d vector. I want to sort it by the value in its 4th column. For example I want to sort this vector:

vector<vector<double>> vector1 = {{4,3,5,3}, 
                                  {2,6,3,7}, 
                                  {6,8,5,1}, 
                                  {5,6,1,5}};

I want to sort its rows by the value in the 4th column, so that its elements position within the rows are unchanged but the rows position within the vector is altered so that the elements in the 4th column are in this order:

 vector1 = {{6,8,5,1},
            {4,3,5,3},
            {5,6,1,5},
            {2,6,3,7}};

I am assuming I will have to use sort(), but after searching around online I still honestly have absolutely no idea how to go about this, so any direct help with the code or even directions to websites or resources would be really appreciated. Thanks!

like image 931
jdough Avatar asked Aug 03 '17 21:08

jdough


1 Answers

Use std::sort with a custom predicate, eg:

std::sort(vector1.begin(),
          vector1.end(),
          [] (const std::vector<double> &a, const std::vector<double> &b)
          {
              return a[3] < b[3];
          });

(with appropriate error checking, of course).

This sorts each item of the "outer vector" (each item being a 1D vector corresponding to a row) with respect to the given predicate, which orders them by their 4th element (the 4th column in the "row").

As detailed in the docs, the predicate should take two items and return true if the first is "strictly less" than the other, and false otherwise. When comparing numeric types this is nice and easy, as we can just use the < operator. And in your case, one "row" is "less than" another if the 4th element is less than.

Edit: See here for working demo.

like image 144
hnefatl Avatar answered Nov 13 '22 14:11

hnefatl