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?

3
  • 4
    related/dupe: stackoverflow.com/questions/20931669/… Commented Oct 14, 2016 at 15:38
  • Your compiler really said long[2]*? Commented Oct 14, 2016 at 15:55
  • @aschepler Exactly! Commented Oct 14, 2016 at 17:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I did not know that std::array used as a value_type for std::array would be sortable. Neat! coliru.stacked-crooked.com/a/a232eca55a5fa6cb
error: the value of ‘N’ is not usable in a constant expression array<array<long, 2>, N> arr;
Yes, you cannot have arrays of variable size in C++. If you're using it as a gcc extension, use array<long, 2> arr[n] and then sort(arr, arr+n);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.