Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a CArray of a user defined type?

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

like image 286
Steve Duitsman Avatar asked Oct 28 '08 19:10

Steve Duitsman


1 Answers

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.

like image 56
Shog9 Avatar answered Sep 28 '22 10:09

Shog9