How to: Sort Arrays Using Custom Criteria
To sort arrays containing simple intrinsic types, you can simply call the Array::Sort method, but to sort arrays containing complex types or to override the default sort criteria, you can override the IComparable::CompareTo method.
In the following example, a structure called Element
is derived from IComparable, and written to provide a CompareTo method that uses the average of two integers as the sort criteria.
Example
using namespace System;
value struct Element : public IComparable {
int v1, v2;
int CompareTo(Object^ obj) {
Element^ o = dynamic_cast<Element^>(obj);
if (o) {
int thisAverage = (v1 + v2) / 2;
int thatAverage = (o->v1 + o->v2) / 2;
if (thisAverage < thatAverage)
return -1;
else if (thisAverage > thatAverage)
return 1;
return 0;
}
else
throw new ArgumentException
("Object must be of type 'Element'");
}
};
int main() {
array<Element>^ a = gcnew array<Element>(10);
Random^ r = new Random;
for (int i=0; i < a->Length; i++) {
a[i].v1 = r->Next() % 100;
a[i].v2 = r->Next() % 100;
}
Array::Sort( a );
for (int i=0; i < a->Length; i++) {
int v1 = a[i].v1;
int v2 = a[i].v2;
int v = (v1 + v2) / 2;
Console::WriteLine("{0} (({1}+{2})/2) ", v, v1, v2);
}
}