From 2faf0a7ec5117a7bf0eed377bf213f365fc39bd8 Mon Sep 17 00:00:00 2001 From: Yiheng Wu <36156959+jingkaimori@users.noreply.github.com> Date: Thu, 23 May 2024 11:18:55 +0800 Subject: [PATCH] [22_1] make array iterable with range based for loop --- Kernel/Containers/array.hpp | 3 +++ tests/Kernel/Containers/array_test.cpp | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/Kernel/Containers/array.hpp b/Kernel/Containers/array.hpp index 9d3ac45f4..bb6a2c074 100644 --- a/Kernel/Containers/array.hpp +++ b/Kernel/Containers/array.hpp @@ -159,6 +159,9 @@ template 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); diff --git a/tests/Kernel/Containers/array_test.cpp b/tests/Kernel/Containers/array_test.cpp index deb5f7b4c..55209d655 100644 --- a/tests/Kernel/Containers/array_test.cpp +++ b/tests/Kernel/Containers/array_test.cpp @@ -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); +}