Skip to content

Commit

Permalink
utlarray.h add sort methods
Browse files Browse the repository at this point in the history
  • Loading branch information
s1lentq committed Dec 13, 2023
1 parent 34e56f6 commit e6d25ba
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions regamedll/public/utlarray.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
#include "tier0/platform.h"
#include "tier0/dbg.h"

#include <algorithm>

#define FOR_EACH_ARRAY(vecName, iteratorName)\
for (int iteratorName = 0; (vecName).IsUtlArray && iteratorName < (vecName).Count(); iteratorName++)

Expand Down Expand Up @@ -71,6 +73,15 @@ class CUtlArray

bool HasElement(const T &src) const;

// sort using std:: and expecting a "<" function to be defined for the type
void Sort();
void Sort(bool (*pfnLessFunc)(const T &src1, const T &src2));
void Sort(int (__cdecl *pfnCompare)(const T *, const T *));

// sort using std:: with a predicate. e.g. [] -> bool (const T &a, const T &b) const { return a < b; }
template <class F>
void SortPredicate(F &&predicate);

protected:
T m_Memory[MAX_SIZE];
};
Expand Down Expand Up @@ -180,6 +191,43 @@ inline int CUtlArray<T, MAX_SIZE>::InvalidIndex()
return -1;
}

// Sort methods
template <typename T, size_t MAX_SIZE>
void CUtlArray<T, MAX_SIZE>::Sort()
{
std::sort(Base(), Base() + Count());
}

template <typename T, size_t MAX_SIZE>
void CUtlArray<T, MAX_SIZE>::Sort(bool (*pfnLessFunc)(const T &src1, const T &src2))
{
std::sort(Base(), Base() + Count(),
[pfnLessFunc](const T &a, const T &b) -> bool
{
if (&a == &b)
return false;

return (*pfnLessFunc)(a, b);
});
}

template <typename T, size_t MAX_SIZE>
void CUtlArray<T, MAX_SIZE>::Sort(int (__cdecl *pfnCompare)(const T *, const T *))
{
typedef int (__cdecl *QSortCompareFunc_t)(const void *, const void *);
if (Count() <= 1)
return;

qsort(Base(), Count(), sizeof(T), (QSortCompareFunc_t)(pfnCompare));
}

template <typename T, size_t MAX_SIZE>
template <class F>
void CUtlArray<T, MAX_SIZE>::SortPredicate(F &&predicate)
{
std::sort(Base(), Base() + Count(), predicate);
}

template <typename T, size_t MAX_SIZE>
void CUtlArray<T, MAX_SIZE>::CopyArray(const T *pArray, size_t count)
{
Expand Down

0 comments on commit e6d25ba

Please sign in to comment.