From 84846a5619584d574e02e6e710bf537de1a668d2 Mon Sep 17 00:00:00 2001 From: karl Date: Mon, 15 Mar 2021 14:22:04 +0100 Subject: [PATCH] Add erase by swap --- Vector.h | 12 ++++++++++++ test.cpp | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/Vector.h b/Vector.h index 44f86e6..5cd8690 100644 --- a/Vector.h +++ b/Vector.h @@ -105,6 +105,18 @@ class Vector { } } + // Erase an element by swapping the previously last element to its place + void erase_by_swap(unsigned int position) { + assert(position < element_count); + + // Swap the last element to this position + std::swap(data[position], data[element_count - 1]); + + // Delete the previous element at this position (now last) + data[element_count - 1].~T(); + element_count--; + } + T *as_array() const { return data; } diff --git a/test.cpp b/test.cpp index c95ad61..69f0f7c 100644 --- a/test.cpp +++ b/test.cpp @@ -275,4 +275,25 @@ SCENARIO("Non-default constructor", "[vector]") { } } } +} + +SCENARIO("Erase by swap", "[vector]") { + GIVEN("A vector with some elements") { + Vector v(3); + v.push_back(1); + v.push_back(2); + v.push_back(3); + + WHEN("Erasing-by-swap the first element") { + v.erase_by_swap(0); + + THEN("The size should have decrease by one") { + REQUIRE(v.size() == 2); + } + + THEN("The previously last element should now be the first") { + REQUIRE(v[0] == 3); + } + } + } } \ No newline at end of file