VC++
Sample: Quick Sort for CStringArray
|
|
Chris Losinger.
Environment:
Tested on VC++
6.0
These
three routines can be used to perform a qsort on a CStringArray.
It is a fairly simple hack, but still a hack. It
sure is fast, though.
// first, declare these somewhere
void SortStringArray (CStringArray& ar, BOOL bDescending);
int CompareDescending(const void *a, const void *b);
int CompareAscending(const void *a, const void *b);
// put something in your CString array
CStringArray bob;
bob.Add("Are");
bob.Add("You");
bob.Add("Talking");
bob.Add("To");
bob.Add("Me?");
// sort it
SortStringArray(bob, TRUE);
// here's the code!
//////////////////////////////////////////////////////////////////////////
int CompareAscending(const void *a, const void *b)
{
CString *pA = (CString*)a;
CString *pB = (CString*)b;
return (pA->Compare(*pB));
}
//////////////////////////////////////////////////////////////////////////
int CompareDescending(const void *a, const void *b)
{
CString *pA = (CString*)a;
CString *pB = (CString*)b;
return (-1 * (pA->Compare(*pB)));
}
//////////////////////////////////////////////////////////////////////////
void SortStringArray (CStringArray& csa, BOOL bDescending)
{
int iArraySize = csa.GetSize();
if (iArraySize <= 0)
return;
int iCSSize = sizeof (CString*);
void* pArrayStart = (void *)&csa[0];
if (bDescending)
qsort (pArrayStart, iArraySize, iCSSize, CompareDescending);
else
qsort (pArrayStart, iArraySize, iCSSize, CompareAscending);
}
|