#include "vec.h" #include #include #include #include Vec::Vec() : Vec(INITIAL_LEN) {} Vec::Vec(std::size_t size) : cap(size), w_idx(0), arr(new T[size]) { std::cout << "Allocating vector of size " << size << std::endl; } Vec::Vec(std::initializer_list il) : Vec(il.size()) { for (auto &elem : il) push_back(std::move(elem)); } Vec::~Vec() { std::cout << "De-allocating vector" << std::endl; if (arr) delete[] arr; } T &Vec::operator[](std::size_t idx) const noexcept { if (idx < w_idx) return arr[idx]; exit(1); } void Vec::push_back(const T &value) { arr[w_idx++] = value; if (w_idx == cap) resize(cap * 2); } void Vec::push_back(T &&value) { arr[w_idx++] = std::move(value); if (w_idx == cap) resize(cap * 2); } std::size_t Vec::size() const { return w_idx; } std::size_t Vec::capacity() const noexcept { return cap; } void Vec::resize(std::size_t newsize) { std::cout << "Reallocating: " << cap << " to " << newsize << std::endl; T *newarr = new T[newsize]; std::move(arr, arr + w_idx, newarr); delete[] arr; arr = newarr; cap = newsize; } void Vec::pop_back() noexcept { --w_idx; } void Vec::clear() noexcept { #ifdef REALCLEAR delete[] arr; arr = new T[INITIAL_LEN]; cap = INITIAL_LEN; #endif w_idx = 0; }