Files
CDAG/Research/core/Util/SmallDynamicArray.h

65 lines
1.8 KiB
C++

#pragma once
#pragma warning(disable:4996)
#include "../Defines.h"
#include <algorithm>
#include <vector>
// Wrapper for standard C array that attempts to minimize memory usage. The user of this class should keep track of the size of the array to correctly be able to insert etc.
template<typename T>
class SmallDynamicArray
{
public:
SmallDynamicArray() : mData(NULL) {}
SmallDynamicArray(size_t size) : mData(new T[size]) {}
SmallDynamicArray(SmallDynamicArray&& source) // Move ctor
{
mData = source.mData;
source.mData = NULL;
}
~SmallDynamicArray() { if (mData != NULL) delete[] mData; }
SmallDynamicArray& operator=(SmallDynamicArray&& source) // Move assignment operator
{
mData = source.mData;
source.mData = NULL;
return *this;
}
inline void Set(const size_t& i, T value) { mData[i] = value; }
inline T& Get(const size_t& i) const { return mData[i]; }
inline T& operator[](const size_t& i) const { return mData[i]; }
inline void SetRange(const T* source, size_t begin, size_t end) { std::copy(source + begin, source + end, mData); }
void Clear() { delete[] mData; mData = NULL; }
inline bool IsEmpty() const { return mData == NULL; }
void Resize(size_t oldSize, const size_t& newSize)
{
T* newData = new T[newSize];
if (!IsEmpty())
{
std::copy(mData, mData + std::min(oldSize, newSize), newData);
delete[] mData;
}
mData = newData;
}
void Insert(size_t index, const T& value, size_t curSize)
{
unsigned* newData = new unsigned[curSize + 1];
// Move the data over to a new array with the correct size
if (mData != NULL)
{
std::copy(mData, mData + index, newData);
std::copy(mData + index, mData + curSize, newData + index + 1);
delete[] mData;
}
newData[index] = value;
mData = newData;
}
private:
T* mData;
};