3

I have such array:

long my_array_left[n][2];

I wrote comparator function for it, which takes array of two elements and sort by first element of array:

struct sort_left {
    bool operator()(const long &left[2], const long &right[2]) {
        return left[0] < right[0];
    }
}

Then I use library function std::sort for sorting my_array_left[n][2]

sort(begin(my_array_left), end(my_array_left), sort_left());

But I have an error: parameter type mismatch: Incompatible pointer types 'long **' and 'long[2]*'.

How can I overcome it?

kotokbek
  • 103
  • 1
  • 8

1 Answers1

4

Your immediate problem can be fixed by having a comparator that actually takes references to arrays instead of references to pointers:

struct sort_left {
    bool operator()(const long (&left)[2], const long (&right)[2]) {
        return left[0] < right[0];
    }
};

But since you can't assign an array to another array, your code won't compile anyway.

You can avoid this by using std::array:

array<array<long, 2>, N> arr{};
sort(arr.begin(), arr.end());

The added benefit is that operator< is automatically defined if array's value_type that defines it.

krzaq
  • 16,240
  • 4
  • 46
  • 61
  • I did not know that `std::array` used as a `value_type` for `std::array` would be sortable. Neat! http://coliru.stacked-crooked.com/a/a232eca55a5fa6cb – caps Oct 14 '16 at 16:13
  • error: the value of ‘N’ is not usable in a constant expression array, N> arr; – kotokbek Oct 14 '16 at 17:38
  • Yes, you cannot have arrays of variable size in C++. If you're using it as a gcc extension, use `array arr[n]` and then `sort(arr, arr+n);` – krzaq Oct 14 '16 at 17:39