Using the ElementComparator object


#1

Could anyone possible give me a basic example of how to create an ElementComparator object and how to use it with the Array::sort() function? My current understanding of template parameters just isn’t getting me anywhere!
Thanks.


#2

Did you look at the DefaultElementComparator for an example?

//==============================================================================
/**
    A simple ElementComparator class that can be used to sort an array of
    objects that support the '<' operator.

    This will work for primitive types and objects that implement operator<().

    Example: @code
    Array <int> myArray;
    DefaultElementComparator<int> sorter;
    myArray.sort (sorter);
    @endcode

    @see ElementComparator
*/
template <class ElementType>
class DefaultElementComparator
{
private:
    typedef PARAMETER_TYPE (ElementType) ParameterType;

public:
    static int compareElements (ParameterType first, ParameterType second)
    {
        return (first < second) ? -1 : ((second < first) ? 1 : 0);
    }
};

Basically, you drop the whole template aspect to this bit of code, and replace ParameterType with the type you require (that your Array<> requires?). Although not a useful example, per sé, say a primitive type like float;

class FloatElementComparator
{
public:
    static int compareElements (float first, float second)
    {
        return (first < second) ? -1 : ((second < first) ? 1 : 0);
    }
};

#3

D’oh, I skimmed right over that example. Many thanks for the help!