ivanseidel / LinkedList

🔗 A fully implemented LinkedList made to work with general Microcontrollers and Arduino projects
MIT License
347 stars 120 forks source link

sort for class objects? #32

Closed michelep closed 2 years ago

michelep commented 5 years ago

How use sort for class objects?

Raincode commented 5 years ago

the sort member function takes the comparison function for two Objects of type T as an argument: int (*cmp)(T &, T &)

simply define a function which does this for your class. I'm not sure, but I'm guessing the return value works similar to strcmp.

class Foo {
// ...
};

int compare_Foo(Foo& lhs, Foo& rhs) {
  // ...
}

LinkedList<Foo> list;
// ...
list.sort(compare_Foo);

P.S.: The signature should be changed to take const T&, since comparing musn't modify objects. But unless the implementation of sort is changed, you will have to use "plain" references.

I don't know if Arduino supports operator overloading, but overloading ==, <, > etc. would be preferable imho. However this would require changes in the implementation of sort as well.

ivanseidel commented 2 years ago

I suppose arduino doesnt support sorting like that, but would be nice to see it working on other platforms!