【问题标题】:Compile error while sorting array of custom structs对自定义结构数组进行排序时编译错误
【发布时间】: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&lt;(const s&amp; other) const { return this-&gt;number &lt; other.number; } 不要忽视const
  • 它应该是arr+10arr+9 错过了数组的最后一个元素。
  • ... 和#include &lt;iterator&gt; 然后做std::sort(std::begin(arr), std::end(arr));
  • This is a much better reference。其次,如果你去那个链接,你必须传递的参数是迭代器,而不是数组中的值。指针用作迭代器。

标签: c++ arrays sorting


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多