简体   繁体   中英

How to sort array of arrays by std::sort?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM