Skip to content

Commit

Permalink
AK: Implement reverse iterator for Vector class
Browse files Browse the repository at this point in the history
  • Loading branch information
guerinoni authored and awesomekling committed Mar 9, 2022
1 parent 74650b4 commit b0e74a3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions AK/Vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down Expand Up @@ -693,12 +694,15 @@ requires(!IsRvalueReference<T>) class Vector {

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
Expand Down
26 changes: 26 additions & 0 deletions Tests/AK/TestVector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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--);
}

0 comments on commit b0e74a3

Please sign in to comment.