How to sort CArray<double, double> with quick sort

F

Frank King

Hi,

I am using CArray and quick sort funciton to sort an array
of double type of data points. I found an article in MSDN

HOWTO: Quick Sorting Using MFC CArray-Derived Classes
ID: Q216858

The article works well with CStringArray. But when I wrote
the following code about double type. It does not work for
me, even though I use

class CSortableDoubleArray : public
CArray<double,double>

directly (without using CDoubleArray). The problem happens
when the second Add() is called:

tmp = 2.0;
MyArray.Add(tmp);

At this point, the program dies inside SetAtGrow() after

delete[] (BYTE*)m_pData;

I think this is the problem mentioned in Q216858. Could
anybody help?

Thank you very much.

fk

------------------- program -------------------------------

class CDoubleArray : public CArray<double,double>
{
public:
CDoubleArray()
{
m_pData = NULL;
m_nSize = m_nMaxSize = m_nGrowBy = 0;
}
~CDoubleArray()
{
}

CDoubleArray(const CDoubleArray& Src)
{
ASSERT_VALID(this);
ASSERT(this != &Src);

SetSize(Src.m_nSize);

const double * pSrcValues = Src.GetData();
for (int j = 0; j <= Src.GetUpperBound();
j++)
{
m_pData[j] = pSrcValues[j];
}
}

const CDoubleArray& operator = (const
CDoubleArray& Src)
{
double * pValues = GetData();
for (int j = 0; j <= GetUpperBound(); j++)
(*this).Add(pValues[j]);

return (*this);
}

protected:

};


typedef int (__cdecl *GENERICCOMPAREFN)(const void *
elem1, const void * elem2);


class CSortableDoubleArray : public CDoubleArray
{
public:

void Sort(GENERICCOMPAREFN pfnCompare = Compare);
double GetMedian();

protected:
static int __cdecl Compare(const void * pValue1,
const void * pValue2);
};

int CSortableDoubleArray::Compare(const void * pValue1,
const void * pValue2)
{
ASSERT(pValue1);
ASSERT(pValue2);
return ((*((double*)pValue1)) > (*((double*)
pValue2)));
}

void CSortableDoubleArray::Sort(GENERICCOMPAREFN
pfnCompare /*= CSortDoubleArray::Compare */)
{
double * prgdbl = GetData();
qsort(prgdbl, GetSize(), sizeof(double),
(GENERICCOMPAREFN)pfnCompare);
}


nt main(int argc, char* argv[])
{

CSortableDoubleArray MyArray;
double tmp = 1.0;
MyArray.Add(tmp);
tmp = 2.0;
MyArray.Add(tmp);
MyArray.Sort();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top