cpp_prac/vector/vec.cc

69 lines
1.3 KiB
C++
Raw Normal View History

2025-01-10 08:15:31 +01:00
#include "vec.h"
#include <cstddef>
#include <cstring>
#include <iostream>
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
}
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);
}
void Vec::push_back(const T &value) {
2025-01-10 08:15:31 +01:00
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)
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) {
std::cout << "Reallocating: " << cap << " to " << newsize << std::endl;
2025-01-10 08:15:31 +01:00
T *newarr = new T[newsize];
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;
}