如何通过std::sort对数组排序?

时间:2022-12-27 19:18:02

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]

然后我使用库函数std::sort对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]*'.

但是我有一个错误:参数类型不匹配:不兼容的指针类型“long **”和“long[2]*”。

How can I overcome it?

我如何克服它?

1 个解决方案

#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:

可以通过使用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.

附加的好处是,如果数组的value_type定义了操作符,那么操作符 <是自动定义的。< p>

#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:

可以通过使用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.

附加的好处是,如果数组的value_type定义了操作符,那么操作符 <是自动定义的。< p>