|
| 1 | +#pragma once |
| 2 | + |
| 3 | +// This is internal headerfile to be included by vector.h only |
| 4 | + |
| 5 | +#include <vector.h> |
| 6 | +#include <new.h> |
| 7 | +#include <stdlib.h> |
| 8 | +#include <string.h> |
| 9 | + |
| 10 | +namespace std { |
| 11 | + |
| 12 | +static std::size_t next_power2(std::size_t size) { |
| 13 | + // assumes no overflow |
| 14 | + std::size_t p = 1; |
| 15 | + while (p && p < size) p <<= 1; |
| 16 | + return p; |
| 17 | +} |
| 18 | + |
| 19 | +template <typename T> |
| 20 | +vector<T>::vector() : _data(NULL), _size(0) { |
| 21 | + resize_capacity(1); |
| 22 | +} |
| 23 | + |
| 24 | +template <typename T> |
| 25 | +vector<T>::vector(std::size_t size, const T &_default): _size(size) { |
| 26 | + this->_data = NULL; |
| 27 | + resize_capacity(size); |
| 28 | + for(std::size_t i = 0; i < size; i++) { |
| 29 | + this->_data[i] = _default; |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +template <typename T> |
| 34 | +void vector<T>::resize_capacity(std::size_t capacity) { |
| 35 | + // internal; assumes capacity to be power of 2 |
| 36 | + // and will also make a copy of array and move _data pointer. |
| 37 | + // assumes size<=current_capacity and size<=new_capacity |
| 38 | + this->_capacity = capacity; |
| 39 | + const std::size_t data_size = capacity*sizeof(T); |
| 40 | + T *_new_data = (T*) std::malloc(data_size); |
| 41 | + if (!_new_data) return; // malloc failed |
| 42 | + std::memcpy(_new_data, this->_data, data_size); |
| 43 | + std::free(this->_data); // should be no-op if _data == NULL |
| 44 | + this->_data = _new_data; |
| 45 | +} |
| 46 | + |
| 47 | +template <typename T> |
| 48 | +bool vector<T>::empty() { |
| 49 | + return this->_size == 0; |
| 50 | +} |
| 51 | + |
| 52 | +template <typename T> |
| 53 | +std::size_t vector<T>::size() { |
| 54 | + return this->_size; |
| 55 | +} |
| 56 | + |
| 57 | +template <typename T> |
| 58 | +void vector<T>::push_back(const T &val) { |
| 59 | + if(this->_size == this->_capacity) { |
| 60 | + resize_capacity(this->_capacity*2); |
| 61 | + } |
| 62 | + this->_data[this->_size++] = val; |
| 63 | +} |
| 64 | + |
| 65 | +template <typename T> |
| 66 | +void vector<T>::pop_back() { |
| 67 | + // not reducing the capacity for now |
| 68 | + if(this->_size > 0) { |
| 69 | + this->_size--; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +template <typename T> |
| 74 | +T &vector<T>::back() { |
| 75 | + return this->_data[this->_size-1]; |
| 76 | +} |
| 77 | +template <typename T> |
| 78 | +T &vector<T>::front() { |
| 79 | + return this->_data[0]; |
| 80 | +} |
| 81 | + |
| 82 | +template <typename T> |
| 83 | +T &vector<T>::at(std::size_t pos) { |
| 84 | + return this->_data[pos]; |
| 85 | +} |
| 86 | + |
| 87 | +template <typename T> |
| 88 | +T &vector<T>::operator[](std::size_t pos) { |
| 89 | + return this->_data[pos]; |
| 90 | +} |
| 91 | + |
| 92 | +} // namespace std end |
0 commit comments