61 lines
1.1 KiB
C++
61 lines
1.1 KiB
C++
|
#include "vec.h"
|
||
|
#include <cstddef>
|
||
|
#include <cstring>
|
||
|
#include <iostream>
|
||
|
|
||
|
Vec::Vec() : cap(INITIAL_LEN), w_idx(0), arr(nullptr) {
|
||
|
std::cout << "Allocating vector" << std::endl;
|
||
|
arr = new T[INITIAL_LEN];
|
||
|
}
|
||
|
|
||
|
Vec::Vec(std::initializer_list<T> il) : Vec() {
|
||
|
for (auto &a : il) push_back(a);
|
||
|
}
|
||
|
|
||
|
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) noexcept {
|
||
|
arr[w_idx++] = 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" << std::endl;
|
||
|
T *newarr = new T[newsize];
|
||
|
std::memcpy(newarr, arr, w_idx);
|
||
|
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;
|
||
|
}
|