Are there any examples on how to use this? Basically, I have an array of objects of a class I defined, and the class contains an int and I want to sort by the value of that int. How easy would this be?
Err…
eh?
Ok, here’s what I’m trying right now that’s not working…
i have a class SampleData with these variables:
StringArray files;
Array<int> velLayers;
String name;
int loKey;
int highKey;
int rootKey;
i have no idea how to use operators but i made a guess and came up with this:
bool operator> (const SampleData& other) {
return rootKey>other.rootKey;
}
bool operator< (const SampleData& other) {
return rootKey<other.rootKey;
}
bool operator== (const SampleData& other) {
return rootKey==other.rootKey;
}
is this the right way to do it?
then i have an OwnedArray of type SampleData:
OwnedArray<SampleData> sampsL;
and i want to sort it so i tried this:
FloatElementComparator<SampleData*> sorter;
sampsL.sort(sorter);
but it doesn’t work… i know this is probably my lack of experiance w/ c++ so any help as to where i went wrong would be appreciated…
I might be wrong (I haven’t used FloatElementComparator myself), but isn’t the problem that FloatElementComparator is meant to only be used with floating point data types? I think what you probably want to do is write your own subclass of ElementComparator to handle your SampleData class.
(the operator stuff looks right to me, by the way)
- Niall.
well it compiles ok, it just doesn’t do anything. i took a look at the floatcomparator class and all it does is check to see if a < b a==b or a>b so shouldn’t that just use my custom operators?
Oh, I see what you mean :oops:. Could it perhaps be that you’re initialising the element comparator with a pointer instead of the actual data type then? i.e. it’s comparing two addresses instead of the actual class itself.
- Niall.
that makes sense, so if that’s the case then the easiest way to do it would probably be to subclass elementcomparator… here’s floatcomparator
00224 template <class ElementType>
00225 class FloatElementComparator : public ElementComparator<ElementType>
00226 {
00227 int compareElements (ElementType first,
00228 ElementType second)
00229 {
00230 return (first < second) ? -1
00231 : ((first == second) ? 0
00232 : 1);
00233 }
00234 };
so i have no idea how to change this to work with my type… in java you could just cast to your class and then perform the checks, is there a way to cast like this in c++?
Yeah, basically you just want to write a simple subclass like this:
template <class ElementType>
class NiallsElementComparator : public ElementComparator<ElementType>
{
int compareElements (ElementType first,
ElementType second)
{
return (*first < *second) ? -1
: ((*first == *second) ? 0
: 1);
}
};
i.e. you’re comparing the contents of the object rather than the pointer to it (because first and second in this case are pointers to your SampleData objects, held by the sampsL OwnedArray).
- Niall.
doh, i feel stupid … thank you
No problem
- Niall.