On OwnedArray<>, sort, and ElementComparator<>


I’m new to JUCE; I’m a long time C++ coder but I’m still getting the hang of all this “modern” template flibberdy-jib… I couldn’t find a good example for what I’m trying to do, so I figured I’d try asking here.

It’s like this: I’ve got a database of records:

class Record
String UsefulInfo;
String MoreUsefulInfo;

UniqueIdStringOf() const;
int CompareTo(Record const &r2)
// something like:…
return compare(r2.UniqueIdStringOf());

Such that for each record I can generate a unique identifying string, the goal being to sort these records alphabetically. (I’m keeping the example simple, not efficient…)

So we’ll have something like:

OwnedArray MyDatabase;
Record *r = new Record();
…set various fields
…some time later

OK, so the question is - what goes into sort? It’s an ElementComparator<Record *>. Hmmmmm.

I understand that somehow I have to provide an ElementComparator for the Record type, which implements a specialization for [int compareElements(first, second)] - which in my presumable case, will look something like:

int ???::compareElements(??? first, ??? second)
return first->CompareTo(second);

What I am NOT getting is the correct syntax for writing such a thing. I’ve looked at juce_ElementComparator.h, including the code for IntegerElementComparator and FloatElementComparator, and it doesn’t help.

I think what I’m trying to do here is very simple, only a small handful of lines of code. But what lines of code? Can anyone help?

And - far be it from me to criticize the the API docs - I know it’s a pain, but a sprinkling of canonical examples for this sort of thing can go a very long way toward flattening the learning curve. (I don’t even want to talk about how windowed “Hello World” went for me…) Is a Forum an ideal container for this sort of learning, or perhaps some sort of Wiki might be a more appropriate aggregator of knowledge?

Anyway, I’m having a grand old time learning Juce, hope someone can lend some insight to my problem.

Thanks and Cheers,
Martin Sz.

You subclass the ElementComparator like this:

[code]class RecordComparator : public ElementComparator<Record*>
int compareElements (Record* pFirst, Record* pSecond)
/* handle NULL pointers */

    return pFirst->CompareTo(pSecond);


and then use a RecordComparator instance for your Array sorts.

Excellent. That worked just as advertised. Thanks.