From 2b62e37ccdd0aca5884d438932240b0fab3e65a8 Mon Sep 17 00:00:00 2001 From: karl Date: Mon, 15 Mar 2021 14:08:05 +0100 Subject: [PATCH] Fix resize() with non-default constructor + test --- Vector.h | 29 +++++++++++++++++------------ test.cpp | 10 ++++++++++ 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/Vector.h b/Vector.h index 998127f..dddd414 100644 --- a/Vector.h +++ b/Vector.h @@ -133,7 +133,7 @@ class Vector { // Resize the size of the vector to the given new_size // If this decreases the size, some elements are deleted // If this increases the size, some default-constructed elements are added - void resize(unsigned int new_size) { + void resize(unsigned int new_size, const T &padder = T()) { int difference = new_size - size(); if (difference > 0) { @@ -143,7 +143,7 @@ class Vector { // Add additional default-constructed items for (int i = 0; i < difference; i++) { - data[element_count + i] = T(); + new (data + element_count + i) T(padder); } } else if (difference < 0) { // Call the destructor on all excess items @@ -160,15 +160,26 @@ class Vector { } private: - unsigned int capacity; - unsigned int element_count; + unsigned int capacity; // Number of T objects the Vector could hold + unsigned int + element_count; // Number of T objects the Vector currently holds T *data; - bool is_using_excessive_memory() { + // Return a sensible capacity for the given size (including some + // padding). + unsigned int get_capacity_for_size(unsigned int size) { + return size * 2 + 5; + } + + // Return true if the Vector is holding much more memory (capacity) than it + // currently needs (element_count). + inline bool is_using_excessive_memory() { return 10 + element_count * 2 < capacity; } - bool new_size_exceeds_capacity(unsigned int new_size) { + // Return true if the passed new_size would cause the Vector to exceed the + // current capacity (meaning it must be expanded with `reallocate` first). + inline bool new_size_exceeds_capacity(unsigned int new_size) { return new_size > capacity; } @@ -182,10 +193,4 @@ class Vector { data = new_data; } - - // Return a sensible capacity for the given size (including some - // padding). - unsigned int get_capacity_for_size(unsigned int size) { - return size * 2 + 5; - } }; diff --git a/test.cpp b/test.cpp index 1947a22..57c1207 100644 --- a/test.cpp +++ b/test.cpp @@ -256,5 +256,15 @@ SCENARIO("Non-default constructor", "[vector]") { REQUIRE(non_default_vector[0].a == 1); } } + + WHEN("Creating a vector and resizing it") { + Vector non_default_vector; + + non_default_vector.resize(50, NonDefault(42)); + + THEN("The new elements should correspond to the passed padder") { + REQUIRE(non_default_vector[49].a == 42); + } + } } } \ No newline at end of file