views:

534

answers:

1

Is there a built-in way to sort a CArray in C++?

+2  A: 

std::sort() should work:

CArray<int> arrayOfInts;
arrayOfInts.Add(7);
arrayOfInts.Add(114);
arrayOfInts.Add(3);
std::sort(arrayOfInts.GetData(), arrayOfInts.GetData()+arrayOfInts.GetSize());

This uses the pointer to the first element in the array as the start iterator, and the pointer to one past the last element as the last iterator (should never be dereferenced anyway, so all's well). You could also pass in a custom predicate if the array contained more interesting data:

struct Foo
{
  int val;
  double priority;
};

bool FooPred(const Foo& first, const Foo& second)
{
   if ( first.val < second.val )
      return true;
   if ( first.val > second.val )
      return false;
   return first.priority < second.priority;
}

//... 

   CArray<Foo> bar;
   std::sort(bar.GetData(), bar.GetData()+bar.GetSize(), FooPred);

Oh - and don't use CArray.

Shog9
Just browsing MSDN, I don't see any guarantee that CArray stores data contiguously. I expect it does, but...std::vector initially had this flaw, and the standard was corrected when it was discovered.
Don Wakefield
See here: http://msdn.microsoft.com/en-us/library/yzsdcs85(VS.80).aspx (or just read the source in afxtempl.h). It's not like MFC is a standard so much as a collection of hacks.
Shog9
Thanks, didn't see that one!
Don Wakefield