I have encountered one coding problem regarding sorting a 2D vector (matrix) using a desired criteria using std::sort
from library algorithm
For example let's say I have a 2D vector
1,8,3
1,9,1
1,4,2
^
and I want to sort it by 3rd column (for example growth criteria) So after sorting I want to have a matrix:
1,9,1
1,4,2
1,8,3
^
I know that in order to specify sorting criteria in std::sort
, third function needs to be sent in std::sort
. If it were a 1D vector
it would not be a problem. I would make a lambda inside std::sort
with 2 parameters, compare them and return true/false.
So now you can see the problem I am facing, how can I access specific elements inside a matrix, in my case third column elements and compare them with std::sort
?
#include <iostream>
#include <vector>
#include <algorithm>
void printMatrix(std::vector<std::vector<int>> m) {
for(int i = 0; i < m.size(); i++) {
for(int j = 0; j < m[i].size(); j++) {
std::cout << m[i][j] << " ";
}
std::cout << std::endl;
}
}
int main() {
std::vector<std::vector<int>> m{
{1,8,3},
{1,9,1},
{1,4,2}
};
std::sort(m.begin(), m.end(), [](int a, int b) { // error
// ???
});
printMatrix(m);
return 0;
}
I would not like to use any other external libraries to solve this problem.
Any help is very appreciated! :)
std::sort(m.begin(), m.end(), [](int a, int b) { // error
// ???
});
The value_type
of the iterators returned by m.begin()
and m.end()
is a std::vector<int>
. Hence, your lambda needs to take that type for both of its parameters.
std::sort(m.begin(), m.end(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return a.at(2) < b.at(2);
});
Note: I am using the at()
member function here rather than operator []
to prevent UB should you ever mistakenly attempt to sort by in invalid index.
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