Kylin/DataStructure/DynamicArrayList.h

82 lines
2.5 KiB
C
Raw Normal View History

2023-12-27 10:29:16 +08:00
#ifndef DYNAMICSEQLIST_H
#define DYNAMICSEQLIST_H
#include "ArrayList.h"
#include <initializer_list>
namespace Kylin {
/**
*Capacity不足时1.5
*/
template <typename T>
class DynamicArrayList : public ArrayList<T> {
public:
DynamicArrayList() = default;
DynamicArrayList(size_t capacity) : m_capacity(capacity) {
this->m_array = new T[m_capacity];
if (this->m_array == nullptr) THROW_EXCEPTION(NoEnoughMemoryException, "No enough memory to allocate.");
}
DynamicArrayList(std::initializer_list<T> init) {
this->m_array = new T[init.size()];
if (this->m_array == nullptr) THROW_EXCEPTION(NoEnoughMemoryException, "No enough memory to allocate.");
m_capacity = init.size();
for (auto &value : init) {
this->m_array[this->m_size++] = value;
}
}
DynamicArrayList(DynamicArrayList &&other) {
m_capacity = other.m_capacity;
this->m_array = other.m_array;
this->m_size = other.m_size;
other.m_capacity = 0;
other.m_size = 0;
other.m_array = nullptr;
}
DynamicArrayList(const DynamicArrayList &other) {
this->m_array = new T[other.m_capacity];
if (this->m_array == nullptr) THROW_EXCEPTION(NoEnoughMemoryException, "No enough memory to allocate.");
m_capacity = other.m_capacity;
for (size_t i = 0; i < other.m_size; i++) {
this->m_array[i] = other.m_array[i];
this->m_size++;
}
}
~DynamicArrayList() {
if (this->m_array != nullptr) delete[] this->m_array;
}
void insert(size_t index, const T &value) override {
if (this->m_size >= m_capacity) {
resize(m_capacity * 2);
}
ArrayList<T>::insert(index, value);
}
virtual size_t capacity() const noexcept { return m_capacity; }
void resize(size_t capacity) {
if (capacity == m_capacity) return;
T *array = new T[capacity];
if (array == nullptr) {
THROW_EXCEPTION(NoEnoughMemoryException, "No memory to allocate.");
}
size_t size = this->m_size < capacity ? this->m_size : capacity;
for (size_t i = 0; i < size; i++) {
array[i] = this->m_array[i];
}
this->m_size = size;
m_capacity = capacity;
delete[] this->m_array;
this->m_array = array;
}
private:
size_t m_capacity = 0;
};
} // namespace Kylin
#endif // DYNAMICSEQLIST_H