Kylin/DataStructure/DynamicArray.h
2023-12-27 10:29:16 +08:00

97 lines
2.6 KiB
C++

#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
#include "Array.h"
#include <initializer_list>
namespace Kylin {
template <typename T>
class DynamicArray : public Array<T> {
public:
DynamicArray() = default;
DynamicArray(size_t size) : m_size(size) { this->m_array = makeSpace(size); }
DynamicArray(size_t size, const T &value) : m_size(size) {
auto array = makeSpace(size);
for (size_t i = 0; i < size; i++) array[i] = value;
this->m_array = array;
}
DynamicArray(const DynamicArray &obj) : m_size(obj.m_size) {
this->m_array = makeSpace(m_size);
copy(obj.m_array, obj.m_size, this->m_array, m_size);
}
DynamicArray(std::initializer_list<T> init) {
this->m_size = init.size();
this->m_array = makeSpace(m_size);
auto begin = init.begin();
for (size_t i = 0; i < m_size; i++) {
this->m_array[i] = *begin;
++begin;
}
}
DynamicArray(DynamicArray &&obj) {
m_size = obj.m_size;
this->m_array = obj.m_array;
obj.m_size = 0;
obj.m_array = nullptr;
}
DynamicArray &operator=(DynamicArray &&obj) {
if (this->m_array != nullptr) delete[] this->m_array;
m_size = obj.m_size;
this->m_array = obj.m_array;
obj.m_size = static_cast<size_t>(-1);
obj.m_array = nullptr;
return *this;
}
~DynamicArray() {
if (this->m_array != nullptr) delete[] this->m_array;
}
DynamicArray &operator=(const DynamicArray &obj) {
if (this == &obj) return *this;
auto array = makeSpace(obj.m_size);
copy(obj.m_array, obj.m_size, array, obj.m_size);
update(array, obj.m_size);
return *this;
}
void resize(size_t size) {
T *array = makeSpace(size);
copy(this->m_array, m_size, array, size);
update(array, size);
}
virtual size_t size() const noexcept { return m_size; }
protected:
T *makeSpace(size_t size) {
T *ret = new T[size];
if (ret == nullptr) THROW_EXCEPTION(NoEnoughMemoryException, "No enough memory to alloc...");
return ret;
}
void copy(T *src, size_t old, T *dest, size_t now) {
auto length = now < old ? now : old;
for (size_t i = 0; i < length; i++) {
dest[i] = src[i];
}
}
void update(T *new_array, size_t new_size) {
delete this->m_array;
this->m_array = new_array;
this->m_size = new_size;
}
private:
size_t m_size = 0;
};
} // namespace Kylin
#endif // DYNAMICARRAY_H