Add erase by swap

This commit is contained in:
karl 2021-03-15 14:22:04 +01:00
parent 49b158dafe
commit 84846a5619
2 changed files with 33 additions and 0 deletions

View File

@ -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 { T *as_array() const {
return data; return data;
} }

View File

@ -275,4 +275,25 @@ SCENARIO("Non-default constructor", "[vector]") {
} }
} }
} }
}
SCENARIO("Erase by swap", "[vector]") {
GIVEN("A vector with some elements") {
Vector<int> 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);
}
}
}
} }