From 8f342fe429bcb4da5eb1ea8ed7aebd8803b2a7ea Mon Sep 17 00:00:00 2001 From: MihailRis Date: Sun, 1 Jun 2025 17:15:12 +0300 Subject: [PATCH] add util::stack_vector --- src/util/stack_vector.hpp | 99 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 src/util/stack_vector.hpp diff --git a/src/util/stack_vector.hpp b/src/util/stack_vector.hpp new file mode 100644 index 00000000..e73bbb11 --- /dev/null +++ b/src/util/stack_vector.hpp @@ -0,0 +1,99 @@ +#pragma once + +namespace util { + template + class stack_vector { + public: + stack_vector() : size_(0) {} + + stack_vector(const stack_vector& other) + : size_(other.size_) { + for (int i = 0; i < size_; ++i) { + new (&data_[i]) T(data_[i]); + } + } + + stack_vector(stack_vector&& other) noexcept + : size_(other.size_) { + for (int i = 0; i < size_; ++i) { + new (&data_[i]) T(std::move(other.data_[i])); + } + other.size_ = 0; + } + + stack_vector(const std::initializer_list& init) : size_(0) { + static_assert( + init.size() <= capacity, + "initializer list exceeds stack vector capacity" + ); + for (const auto& value : init) { + new (&data_[size_++]) T(value); + } + } + + ~stack_vector() { + clear(); + } + + void push_back(const T& value) { + if (size_ < capacity) { + data_[size_++] = value; + } else { + throw std::overflow_error("stack vector capacity exceeded"); + } + } + + void pop_back() { + if (size_ > 0) { + data_[size_ - 1].~T(); + --size_; + } else { + throw std::underflow_error("stack vector is empty"); + } + } + + void clear() { + for (int i = 0; i < size_; ++i) { + data_[i].~T(); + } + size_ = 0; + } + + T& operator[](int index) { + return data_[index]; + } + + const T& operator[](int index) const { + return data_[index]; + } + + T& at(int index) { + if (index < 0 || index >= size_) { + throw std::out_of_range("index out of range"); + } + return data_[index]; + } + + const T& at(int index) const { + if (index < 0 || index >= size_) { + throw std::out_of_range("index out of range"); + } + return data_[index]; + } + + int size() const { + return size_; + } + + bool empty() const { + return size_ == 0; + } + + bool full() const { + return size_ == capacity; + } + private: + T data_[capacity]; + int size_; + }; +}