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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With