Skip to content

Commit f4e5d4c

Browse files
committed
Add FixedVector::back()
1 parent ff66522 commit f4e5d4c

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

tests/fixed_vector_tests.cc

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,29 @@ TEST_CASE("Iterator Erase different parts of vector") {
6565
}
6666
}
6767

68-
TEST_CASE("Constructor inits back_idx variable") {
68+
TEST_CASE("Constructor inits size") {
6969
FixedVector<int, 8> a{1, 3, 5};
7070
CHECK(a.size() == 3);
7171
}
7272

73+
TEST_CASE("back() returns default-constructed T with empty vector") {
74+
struct T {
75+
int x = 99999;
76+
};
77+
FixedVector<T, 3> a{T{.x = 1}, T{.x = 3}, T{.x = 5}};
78+
CHECK(a.back().x == 5);
79+
CHECK(a.pop_back().x == 5);
80+
81+
CHECK(a.back().x == 3);
82+
CHECK(a.pop_back().x == 3);
83+
84+
CHECK(a.back().x == 1);
85+
CHECK(a.pop_back().x == 1);
86+
87+
CHECK(a.back().x == 99999);
88+
CHECK(a.pop_back().x == 99999);
89+
}
90+
7391
TEST_CASE("Basic usage: operator[] reads") {
7492
FixedVector<int, 4> a{1, 2, 3, 4};
7593
CHECK(a[0] == 1);

util/fixed_vector.hh

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ public:
2626
return data[idx];
2727
}
2828

29+
T back() const {
30+
if (back_idx > 0)
31+
return data[back_idx - 1];
32+
else
33+
return T{};
34+
}
35+
2936
bool push_back(T el) {
3037
if (back_idx >= MaxElements)
3138
return false;

0 commit comments

Comments
 (0)