2025-01-10 08:15:31 +01:00
|
|
|
#include "vec.h"
|
|
|
|
#include <cstddef>
|
|
|
|
#include <cstring>
|
|
|
|
#include <iostream>
|
|
|
|
|
2025-01-11 17:13:50 +01:00
|
|
|
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;
|
2025-01-10 08:15:31 +01:00
|
|
|
}
|
|
|
|
|
2025-01-11 17:13:50 +01:00
|
|
|
Vec::Vec(std::initializer_list<T> il) : Vec(il.size()) {
|
|
|
|
for (auto &elem : il) push_back(std::move(elem));
|
2025-01-10 08:15:31 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2025-01-11 17:13:50 +01:00
|
|
|
void Vec::push_back(const T &value) {
|
2025-01-10 08:15:31 +01:00
|
|
|
arr[w_idx++] = value;
|
|
|
|
|
2025-01-11 17:13:50 +01:00
|
|
|
if (w_idx == cap)
|
|
|
|
resize(cap * 2);
|
|
|
|
}
|
|
|
|
|
|
|
|
void Vec::push_back(T &&value) {
|
|
|
|
arr[w_idx++] = std::move(value);
|
|
|
|
|
|
|
|
if (w_idx == cap)
|
2025-01-10 08:15:31 +01:00
|
|
|
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) {
|
2025-01-11 17:13:50 +01:00
|
|
|
std::cout << "Reallocating: " << cap << " to " << newsize << std::endl;
|
|
|
|
|
2025-01-10 08:15:31 +01:00
|
|
|
T *newarr = new T[newsize];
|
2025-01-11 17:13:50 +01:00
|
|
|
std::move(arr, arr + w_idx, newarr);
|
2025-01-10 08:15:31 +01:00
|
|
|
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;
|
|
|
|
}
|