首页 > 解决方案 > 对自定义结构数组进行排序时编译错误

问题描述

我做了这个简单的例子来对我的自定义 struct 的数组进行排序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

我已经发现这只发生在数组上,但适用于例如向量。为什么会出现这些错误,我该如何解决?

标签: c++arrayssorting

解决方案


std::sort将迭代器作为参数而不是数组的元素。

考虑到这不能对数组进行排序:

int a[] = {1,2,3,4};  // the array
std::sort(1,4);       // pass first and last element to sort...urks

指向 c 数组中元素的指针是迭代器,您可以使用std::beginand方便地获取它们std::end

s arr[10];
std::sort(std::begin(arr),std::end(arr));

推荐阅读