diff --git a/regamedll/public/utlvector.h b/regamedll/public/utlvector.h index 6dcd250f1..70ed79846 100644 --- a/regamedll/public/utlvector.h +++ b/regamedll/public/utlvector.h @@ -30,6 +30,8 @@ #include "utlmemory.h" +#include + template class CUtlVector { @@ -126,6 +128,20 @@ class CUtlVector // Set the size by which it grows when it needs to allocate more memory. void SetGrowSize(int size); + // 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)); + +#if defined(_WIN32) + void Sort(int (__cdecl *pfnCompare)(const T *, const T *)); +#else + void Sort(int (*pfnCompare)(const T *, const T *)); +#endif + + // sort using std:: with a predicate. e.g. [] -> bool (const T &a, const T &b) const { return a < b; } + template + void SortPredicate(F &&predicate); + protected: // Can't copy this unless we explicitly do it! CUtlVector(CUtlVector const &vec) { assert(0); } @@ -562,3 +578,55 @@ void CUtlVector::SetGrowSize(int size) { m_Memory.SetGrowSize(size); } + +// Sort methods +template +void CUtlVector::Sort() +{ + std::sort(Base(), Base() + Count()); +} + +template +void CUtlVector::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); + }); +} + +#if defined(_WIN32) + +template +void CUtlVector::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)); +} + +#else // #if defined(_LINUX) + +template +void CUtlVector::Sort(int (*pfnCompare)(const T *, const T *)) +{ + typedef int (*QSortCompareFunc_t)(const void *, const void *); + if (Count() <= 1) + return; + + qsort(Base(), Count(), sizeof(T), (QSortCompareFunc_t)(pfnCompare)); +} +#endif // #if defined(_LINUX) + +template +template +void CUtlVector::SortPredicate(F &&predicate) +{ + std::sort(Base(), Base() + Count(), predicate); +}