#pragma once #include namespace fnd { template class Vec { public: // constructors Vec(); Vec(const Vec& other); Vec(const T* array, size_t num); ~Vec(); // copy operator void operator=(const Vec& other); // equivalence operators bool operator==(const Vec& other) const; bool operator!=(const Vec& other) const; // element access const T& operator[](size_t index) const; T& operator[](size_t index); // raw access const T* data() const; T* data(); // element num size_t size() const; // allocate vector void alloc(size_t new_size); // resize vector void resize(size_t new_size); // clear vector void clear(); private: T* m_Vec; size_t m_Size; void copyFrom(const T * array, size_t num); }; template inline Vec::Vec() : m_Vec(nullptr), m_Size(0) {} template inline Vec::Vec(const Vec& other) : Vec() { copyFrom(other.data(), other.size()); } template inline Vec::Vec(const T * array, size_t num) : Vec() { copyFrom(array, num); } template inline Vec::~Vec() { clear(); } template inline void Vec::operator=(const Vec& other) { copyFrom(other.data(), other.size()); } template inline bool Vec::operator==(const Vec& other) const { bool isEqual = true; if (m_Size == other.m_Size) { for (size_t i = 0; i < m_Size && isEqual; i++) { if (m_Vec[i] != other.m_Vec[i]) { isEqual = false; } } } else { isEqual = false; } return isEqual; } template inline bool Vec::operator!=(const Vec& other) const { return !(*this == other); } template inline const T & Vec::operator[](size_t index) const { return m_Vec[index]; } template inline T & Vec::operator[](size_t index) { return m_Vec[index]; } template inline const T * Vec::data() const { return m_Vec; } template inline T * Vec::data() { return m_Vec; } template inline size_t Vec::size() const { return m_Size; } template inline void Vec::alloc(size_t new_size) { clear(); m_Vec = new T[new_size]; if (m_Vec == nullptr) { fnd::Exception("Vec", "Failed to allocate memory for vector"); } m_Size = new_size; } template inline void Vec::resize(size_t new_size) { if (m_Vec != nullptr) { T* new_vec = new T[new_size]; if (new_vec == nullptr) { fnd::Exception("Vec", "Failed to allocate memory for vector"); } for (size_t i = 0; i < _MIN(m_Size, new_size); i++) { new_vec[i] = m_Vec[i]; } delete[] m_Vec; m_Vec = new_vec; m_Size = new_size; } else { alloc(new_size); } } template inline void Vec::clear() { if (m_Vec != nullptr) { delete[] m_Vec; } m_Vec = nullptr; m_Size = 0; } template inline void Vec::copyFrom(const T * array, size_t num) { clear(); alloc(num); for (size_t i = 0; i < m_Size; i++) { m_Vec[i] = array[i]; } } }