From 560abcb2014849f1db8a7c83a292943c045208c0 Mon Sep 17 00:00:00 2001 From: karl Date: Mon, 15 Mar 2021 14:12:22 +0100 Subject: [PATCH] Add as_array --- Vector.h | 9 +++++++-- test.cpp | 18 +++++++++++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/Vector.h b/Vector.h index dddd414..c77460e 100644 --- a/Vector.h +++ b/Vector.h @@ -105,6 +105,10 @@ class Vector { } } + T *as_array() { + return data; + } + // Returns the number of elements in the vector, regardless of the actually // reserved memory. unsigned int size() const { @@ -132,7 +136,8 @@ 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 + // If this increases the size, some default-constructed elements are added. + // If no default constructor is available, a padder must be passed. void resize(unsigned int new_size, const T &padder = T()) { int difference = new_size - size(); @@ -141,7 +146,7 @@ class Vector { reallocate(new_size); } - // Add additional default-constructed items + // Add additional items for (int i = 0; i < difference; i++) { new (data + element_count + i) T(padder); } diff --git a/test.cpp b/test.cpp index 57c1207..c95ad61 100644 --- a/test.cpp +++ b/test.cpp @@ -14,12 +14,20 @@ SCENARIO("Vector size and length are correct", "[vector]") { } SCENARIO("The bracket operator returns the correct element", "[vector]") { - Vector v(20); - v.push_back(1); - v.push_back(2); - v.push_back(3); + GIVEN("A vector with some elements") { + Vector v(20); + v.push_back(1); + v.push_back(2); + v.push_back(3); - REQUIRE(v[1] == 2); + THEN("The element in the middle must have the expected value") { + REQUIRE(v[1] == 2); + } + + THEN("The same value must be accessible using as_array") { + REQUIRE(v.as_array()[1] == 2); + } + } } SCENARIO("Equality is returned correctly", "[vector]") {