我在 Arduino 程序中使用 List (https://github.com/nkaaf/Arduino-List)。我需要能够在数据更新时对列表进行重新排序。文档表明 sort() 方法是从 AbstractList< T > 类继承的。 (https://nkaaf.github.io/Arduino-List/html/class_abstract_list.html)。
据我所知,排序算法采用带有签名的比较器(https://nkaaf.github.io/Arduino-List/html/class_abstract_list.html#a6f18cfb85d7ffd22123cf85d38cad85d)
int(*)(const void *, const void *) compFunc
但是我找不到任何关于如何为自定义类型编写
compFunc()
的示例。
此外,我找不到除签名之外的任何文档或规格,例如返回值应该如何计算。
有人能指出我正确的方向吗?
我尝试编写 compFunc() 像:
int compFunc(const void * a, const void * b) {
return (a.getValue() < b.getValue());
}
方法
getValue()
已在列表中存储的所有类上实现,但出现编译错误:
Compilation error: request for member 'getVal' in 'a', which is of non-class type 'const void*'
我也尝试将
const void *
替换为 a 和 b 的实际类型,但我得到:
Compilation error: passing 'const MyClass' as 'this' argument discards qualifiers [-fpermissive]
我也尝试过不使用
const
关键字,我得到:
Compilation error: invalid conversion from 'int (*)(MyClass*, MyClass*)' to 'int (*)(const void*, const void*)' [-fpermissive]
好的。没关系。我深入研究了
List
的代码,看起来它在排序之前将列表转换为数组。每次调用 sort()
时,它都会为数组分配内存,因此看起来内存泄漏即将发生。特别是如果列表的长度在排序之间发生变化,因此临时数组的大小发生变化,导致更多的碎片机会。我会尝试找到一个可以就地排序的列表实现。
有人可以为 Arduino 推荐一个现成的带有排序的链表吗?