Skip to content

Commit

Permalink
[22_1] make array iterable with range based for loop
Browse files Browse the repository at this point in the history
  • Loading branch information
jingkaimori authored May 23, 2024
1 parent 2e89509 commit 2faf0a7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Kernel/Containers/array.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ template <class T> class array {
* @return A reference to the element at the specified index.
*/
inline T& operator[] (int i) { return rep->a[i]; }

T* begin () { return rep->a; }
T* end () { return rep->a + rep->n; }
};
CONCRETE_TEMPLATE_CODE (array, class, T);

Expand Down
16 changes: 16 additions & 0 deletions tests/Kernel/Containers/array_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,19 @@ TEST_CASE ("array of string") {
arr << "";
CHECK (contains (string (""), arr));
}

TEST_CASE ("test iteration") {
int expectedIndex= 0;
for (const auto element : five_elem) {
CHECK_EQ (element, five_elem[expectedIndex]);
++expectedIndex;
}
CHECK_EQ (expectedIndex, 5);

expectedIndex= 0;
for (const auto element : zero_elem) {
CHECK_EQ (element, zero_elem[expectedIndex]);
++expectedIndex;
}
CHECK_EQ (expectedIndex, 0);
}

0 comments on commit 2faf0a7

Please sign in to comment.