【发布时间】:2020-11-30 19:50:40
【问题描述】:
我制作了这个简单的示例,用于对我的自定义结构 s 的数组进行排序。它有一个operator< 函数,根据cplusplus.com,这就是sort 所需要的全部。
#include <algorithm>
struct s {
int number;
bool operator<(s& other) {
return this->number < other.number;
}
};
int main() {
s arr[10];
std::sort(arr[0], arr[9]);
}
但是,在尝试编译时,我遇到了几个错误:
error C2676: binary '-': 'const _RanIt' does not define this operator or a conversion to a type acceptable to the predefined operator
error C2672: '_Sort_unchecked': no matching overloaded function found
error C2780: 'void std::_Sort_unchecked(_RanIt,_RanIt,iterator_traits<_Iter>::difference_type,_Pr)': expects 4 arguments - 3 provided
我已经发现这只发生在数组上,但适用于例如向量。为什么会出现这些错误,我该如何解决?
【问题讨论】:
-
试试
std::sort(arr, arr+9);arr[0]是数字,不是地址 -
bool operator<(const s& other) const { return this->number < other.number; }不要忽视const。 -
它应该是
arr+10。arr+9错过了数组的最后一个元素。 -
... 和
#include <iterator>然后做std::sort(std::begin(arr), std::end(arr)); -
This is a much better reference。其次,如果你去那个链接,你必须传递的参数是迭代器,而不是数组中的值。指针用作迭代器。