Is there a built-in way to sort a CArray in C++?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With