From: Amelia Coutard Date: Sat, 30 Dec 2023 00:24:19 +0000 (+0100) Subject: Des fonctions de plus pour le vecteur X-Git-Url: https://git.ameliathe1st.gay/?a=commitdiff_plain;h=68d01930df734673beb219edf5f8de3e684c5a88;p=voyage-au-centre-des-fichiers.git Des fonctions de plus pour le vecteur --- diff --git a/libcpp/vector.hpp b/libcpp/vector.hpp index 84577e6..940358f 100644 --- a/libcpp/vector.hpp +++ b/libcpp/vector.hpp @@ -88,23 +88,37 @@ public: assert(!construction_failed()); return capacity_; } + bool reserve(amy::size n) { + assert(!construction_failed()); + if (n <= capacity_) { + return true; + } + T* new_data = (T*)amy::reallocate(allocator, data, capacity_ * amy::byte_size(), n * amy::byte_size(), amy::byte_align()); + if (new_data == amy::nil) { + return false; + } + data = new_data; + capacity_ = n; + return true; + } bool push_back(const T& v) { + return emplace_back(v); + } + template + bool emplace_back(Ts... vs) { assert(!construction_failed()); - if (size_ == capacity_) { - if (allocator.expand(data, capacity_ * amy::byte_size(), amy::byte_size())) { - capacity_++; - } else if (auto new_data = - amy::reallocate(allocator, data, capacity_ * amy::byte_size(), capacity_ * 2 * amy::byte_size(), amy::byte_align())) { - data = (T*)new_data; - capacity_ *= 2; - } else { - return false; - } + if (size_ == capacity_ && !reserve(2 * capacity_)) { + return false; } size_++; - new(&data[size_ - 1]) T(v); + new(&data[size_ - 1]) T(vs...); return true; } + void pop_back() { + assert(size_ > 0); + data[size_ - 1].~T(); + size_--; + } T& operator[](amy::diff i) { assert(!construction_failed()); assert(0 <= i && i < size_);