Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ryanwarsaw
Created February 18, 2018 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanwarsaw/c2f92bcf5bd73e51494a6cffc27c81f2 to your computer and use it in GitHub Desktop.
Save ryanwarsaw/c2f92bcf5bd73e51494a6cffc27c81f2 to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <stdexcept>
template <typename T>
class ArrayList {
private:
int size_; // the size of the LIST
int capacity_; // the size of the backing ARRAY
T *data_; // The pointer to the backing ARRAY of type T
const int kDefaultCapacity = 16;
public:
ArrayList();
ArrayList(int);
~ArrayList();
bool IsEmpty() const;
int size() const;
void Add(const T&);
void Resize();
T& Get(int) const;
T& operator[](int) const;
ArrayList<T>& operator=(ArrayList<T>&);
};
template<typename T>
inline ArrayList<T>::ArrayList() {
this->size_ = 0;
this->capacity_ = kDefaultCapacity;
this->data_ = new T[kDefaultCapacity];
}
template<typename T>
inline ArrayList<T>::ArrayList(int size) {
if (size < kDefaultCapacity) {
throw std::invalid_argument("Invalid size");
} // else, size is ok DoNothing();
this->size_ = 0;
this->capacity_ = size;
this->data_ = new T[size];
}
template<typename T>
inline ArrayList<T>::~ArrayList() {
delete[] this->data_;
}
template<typename T>
inline bool ArrayList<T>::IsEmpty() const {
return this->size() == 0;
}
template<typename T>
inline int ArrayList<T>::size() const {
return this->size_;
}
template<typename T>
inline void ArrayList<T>::Add(const T &value) {
if (this->size() < this->capacity_) {
this->data_[this->size()] = value;
this->size_++;
}
else {
this->Resize();
this->data_[this->size()] = value;
this->size_++;
}
}
template<typename T>
inline void ArrayList<T>::Resize() {
if (this->size() == this->capacity_) {
int new_capacity = (this->capacity_ * 3) / 2 + 1;
T *new_data = new T[new_capacity];
for (int index = 0; index < this->capacity_; index++) {
new_data[index] = std::move(this->data_[index]);
}
this->capacity_ = new_capacity;
std::swap(this->data_, new_data);
delete[] new_data;
} // else, we don't need to resize DoNothing();
}
template<typename T>
inline T & ArrayList<T>::Get(int index) const {
if (index < 0 || index >= this->size()) {
throw std::invalid_argument("Index not within range");
} // else, index is fine DoNothing();
return this->data_[index];
}
template<typename T>
inline T & ArrayList<T>::operator[](int index) const {
return this->Get(index);
}
template<typename T>
inline ArrayList<T>& ArrayList<T>::operator=(ArrayList<T>& rhs) {
std::swap(this->size_, rhs.size_);
std::swap(this->capacity_, rhs.capacity_);
std::swap(this->data_, rhs.data_);
return *this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment