Friday, November 14, 2014

How to create and use your own custom compare method for STL classes?


As you may have known, the STL libraries provide you with a vast collection of classes and algorithms that you can use in your program.
Some of the most popular data structure classes that you may have known are vector and set.
In this articular article, I will talk about both with examples.

STL::set<YourClass>   variable;

Typically this would be your declaration for a set. Notice a set always have unique elements in it that's why sorting is required to help determine if a new element is already existed in the set. Therefore, the elements are already sorted in some default order. The next question is what if you don't like the default sorting.  Let's say you want to sort by the typeID of the object.
If this is the case, you will have to create  you own compare method:

STL::set<YourClass, CompareMethod> variable;

Let's say your class name is Object and the compare method is call SortByType.

STL::set<Object, SortByType> variable;

You would declare your compare method like this:

struct SortByType
{
bool operator()(const Object & object1, const Object & object2)
{
return (object1->GetInterfaceMetaClass()->GetTypeID() > object2->GetInterfaceMetaClass()->GetTypeID());
}
};


Now you can copy the content from the set with default sorting to the your new set:

SLT::set<Object> originalSet;

STL::set<Object, SortByType> newSet(originalSet.begin(), originalSet.end());


If you want to copy to a vector, then you can insert and then sort your vector.

bool SortByType(const RefARpObject & object1, const RefARpObject & object2)
{
return (object1->GetInterfaceMetaClass()->GetTypeID() > object2->GetInterfaceMetaClass()->GetTypeID());
}

STL::vector<Object> vect;
vect.insert(originalSet.begin(), originalSet.end());

STL::sort(vect.begin(), vect.end(), SortByType);

Notice the declaration for SortByType used in the set template are different than the one used by the
sort algorithm.