0

I need to sort an array in decreasing order of the first element in subarray. e.g. if I have the array

3 4
5 6
1 2

It needs to be sorted based on the first element of each row, so it would be

1 2
3 4
5 6

Currently this is what I have, but as expected it doesn't work:

#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;

bool compare(int a[], int b[]){
    // cout << arr;
    return a[0] > b[0];
}

int main(){
    int arr[3][2] = {
        {3, 4},
        {5, 6},
        {1, 2}
    };
    sort(arr, arr + 3, compare);
    cout << arr[0][0] << " " << arr[0][1] << endl;
    cout << arr[1][0] << " " << arr[1][1] << endl;
    cout << arr[2][0] << " " << arr[2][1];
}

The problem probably has to do with my understanding of how pointers work on 2d arrays. I'm a java main, so the whole pointer concept and the concept of passing a function as a parameter is new to me. Wonder how to fix the code, as well as tips on how to learn/use pointers?

F777
  • 103
  • 6
  • 1
    There are no 2-D arrays (C-style arrays that is). Think of `arr` as an array of 3 elements, each element of which is an array of 2 ints . `std::sort` cannot be used this way as it sorts elements by value and C-style arrays can't be copied by value . You could use `std::array` instead which does have value semantics. – M.M May 17 '21 at 04:24
  • `arr` is an array of **3** elements. `arr + 6` will be far out of bounds. – Some programmer dude May 17 '21 at 04:28
  • 1
    https://stackoverflow.com/a/20931879/1505939 – M.M May 17 '21 at 04:31

0 Answers0