c++ - 对自定义结构数组进行排序时编译错误
问题描述
我做了这个简单的例子来对我的自定义 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
我已经发现这只发生在数组上,但适用于例如向量。为什么会出现这些错误,我该如何解决?
解决方案
std::sort
将迭代器作为参数而不是数组的元素。
考虑到这不能对数组进行排序:
int a[] = {1,2,3,4}; // the array
std::sort(1,4); // pass first and last element to sort...urks
指向 c 数组中元素的指针是迭代器,您可以使用std::begin
and方便地获取它们std::end
:
s arr[10];
std::sort(std::begin(arr),std::end(arr));
推荐阅读
- apache-kafka - 从 kafka 代理中查找最后插入的值
- excel - 比较 2 张单独工作表上的多列并显示“匹配”或“不匹配?
- python - Elastix 3D 注册停止 python 没有任何错误
- elasticsearch - 我在弹性搜索上有我的“实体”-如何使用 JTS 更新我的“geom”列(我想对我的 GEOM 列执行更新查询)
- docker - 带有 systemctl 的 Docker
- java - 如何为扩展父编号的树实体对象编号?
- asp.net - 使用没有 SPA 代理的 ASP.Net Core React.js 模板
- html - Outlook 2019 背景颜色渲染错误
- android - 我想在 Firebase 消息传递中创建推送拒绝
- sql-server - XML如何从除根以外的所有节点中删除命名空间?