66 lines
2.0 KiB
C++
66 lines
2.0 KiB
C++
#ifndef SEQLIST_H
|
|
#define SEQLIST_H
|
|
|
|
#include "Exception.h"
|
|
#include "List.h"
|
|
#include "RandomIterator.h"
|
|
|
|
namespace Kylin {
|
|
|
|
template <typename T>
|
|
class ArrayList : public List<T> {
|
|
public:
|
|
static const size_t npos = static_cast<size_t>(-1);
|
|
using Iterator = RandomIterator<T>;
|
|
|
|
void append(const T &value) override { return insert(m_size, value); }
|
|
|
|
void insert(size_t index, const T &value) override {
|
|
if (m_size >= capacity()) THROW_EXCEPTION(InvalidParameterException, "There is no capacity.");
|
|
if (index > m_size) index = m_size;
|
|
for (int i = m_size - 1; i >= static_cast<int>(index); i--) {
|
|
m_array[i + 1] = m_array[i];
|
|
}
|
|
m_array[index] = value;
|
|
m_size++;
|
|
}
|
|
|
|
T &last() override {
|
|
if (m_size <= 0) THROW_EXCEPTION(InvalidOperationException, "There is no element in the container.");
|
|
return m_array[m_size - 1];
|
|
}
|
|
|
|
void removeAt(size_t index) override {
|
|
if (index >= m_size) THROW_EXCEPTION(IndexOutOfBoundsException, "The index is out of range.");
|
|
for (auto i = index + 1; i < m_size; i++) {
|
|
m_array[i - 1] = m_array[i];
|
|
}
|
|
m_size--;
|
|
}
|
|
virtual void clear() noexcept { m_size = 0; }
|
|
virtual size_t size() const noexcept { return m_size; }
|
|
|
|
size_t indexOf(const T &value, size_t from = 0) const override {
|
|
for (size_t i = from; i < m_size; i++) {
|
|
if (m_array[i] == value) return i;
|
|
}
|
|
return npos;
|
|
}
|
|
|
|
virtual size_t capacity() const noexcept = 0;
|
|
|
|
T &operator[](size_t index) {
|
|
if (index >= m_size) THROW_EXCEPTION(IndexOutOfBoundsException, "Index is out of bounds...");
|
|
return m_array[index];
|
|
}
|
|
|
|
Iterator begin() { return Iterator(m_array); }
|
|
Iterator end() { return Iterator(m_array + m_size); }
|
|
|
|
protected:
|
|
T *m_array = nullptr;
|
|
size_t m_size = 0;
|
|
};
|
|
} // namespace Kylin
|
|
#endif // SEQLIST_H
|