Add erase by swap
This commit is contained in:
parent
49b158dafe
commit
84846a5619
12
Vector.h
12
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;
|
||||
}
|
||||
|
21
test.cpp
21
test.cpp
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user