AK: Implement reverse iterator for Vector class

This commit is contained in:
Federico Guerinoni 2022-02-23 15:59:00 +01:00 committed by Andreas Kling
parent 74650b4e32
commit b0e74a3fd3
2 changed files with 30 additions and 0 deletions

View file

@ -13,6 +13,7 @@
#include <AK/Forward.h>
#include <AK/Iterator.h>
#include <AK/Optional.h>
#include <AK/ReverseIterator.h>
#include <AK/Span.h>
#include <AK/StdLibExtras.h>
#include <AK/Traits.h>
@ -693,12 +694,15 @@ public:
using ConstIterator = SimpleIterator<Vector const, VisibleType const>;
using Iterator = SimpleIterator<Vector, VisibleType>;
using ReverseIterator = SimpleReverseIterator<Vector, VisibleType>;
ConstIterator begin() const { return ConstIterator::begin(*this); }
Iterator begin() { return Iterator::begin(*this); }
ReverseIterator rbegin() { return ReverseIterator::rbegin(*this); }
ConstIterator end() const { return ConstIterator::end(*this); }
Iterator end() { return Iterator::end(*this); }
ReverseIterator rend() { return ReverseIterator::rend(*this); }
template<typename TUnaryPredicate>
ConstIterator find_if(TUnaryPredicate&& finder) const

View file

@ -533,3 +533,29 @@ TEST_CASE(reference_deletion_should_not_affect_object)
}
EXPECT_EQ(times_deleted, 1u);
}
TEST_CASE(rbegin)
{
Vector<int> v { 1, 2, 3, 4, 5, 6, 7, 8, 0 };
auto const expected = v.begin() + 4;
auto const expected_in_reverse = v.rbegin() + 4;
EXPECT_EQ(*expected, *expected_in_reverse);
}
TEST_CASE(rend)
{
Vector<int> v { 1, 2, 3, 4, 5, 6, 7, 8, 0 };
const auto expected = v.end() - 5;
const auto expected_in_reverse = v.rend() - 5;
EXPECT_EQ(*expected, *expected_in_reverse);
}
TEST_CASE(reverse_loop)
{
Vector<int> v { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int index = 9;
for (auto rev = v.rbegin(); rev != v.rend(); ++rev)
EXPECT_EQ(*rev, index--);
}