Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a 2D vector with specific criteria using std::sort

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! :)

like image 742
galaxyworks Avatar asked Sep 01 '25 17:09

galaxyworks


1 Answers

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

like image 95
WhiZTiM Avatar answered Sep 04 '25 06:09

WhiZTiM