Skip to content

Commit 293631b

Browse files
committed
Updates ZipIterator to support offsetting and std::next/prev
1 parent f65a42d commit 293631b

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

include/mf/zip_iterator.hpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,37 @@ template <typename... IteratorTs> class ZipIterator<std::tuple<IteratorTs...>>
8585
return *this;
8686
}
8787

88+
inline std::ptrdiff_t operator-(const ZipIterator& other) const
89+
{
90+
return std::get<0>(this->ptr_) - std::get<0>(other.ptr_);
91+
}
92+
93+
inline ZipIterator operator-(const std::ptrdiff_t offset) const
94+
{
95+
ZipIterator result{*this};
96+
tuple_for_each([offset](auto& ptr) { ptr -= offset; }, result.ptr_);
97+
return result;
98+
}
99+
100+
inline ZipIterator operator+(const std::ptrdiff_t offset) const
101+
{
102+
ZipIterator result{*this};
103+
tuple_for_each([offset](auto& ptr) { ptr += offset; }, result.ptr_);
104+
return result;
105+
}
106+
107+
inline ZipIterator& operator-=(const std::ptrdiff_t offset)
108+
{
109+
tuple_for_each([offset](auto& ptr) { ptr -= offset; }, ptr_);
110+
return *this;
111+
}
112+
113+
inline ZipIterator& operator+=(const std::ptrdiff_t offset)
114+
{
115+
tuple_for_each([offset](auto& ptr) { ptr += offset; }, ptr_);
116+
return *this;
117+
}
118+
88119
inline ZipIterator& operator--()
89120
{
90121
tuple_for_each([](auto& ptr) { --ptr; }, ptr_);

test/unit/zip_iterator.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,36 @@ TEST(ZipIterator, TraitsNoCommonIteratorCatagory)
6969

7070
ASSERT_TRUE((std::is_same_v<std::iterator_traits<decltype(zip_itr)>::iterator_category, void>));
7171
}
72+
73+
TEST(ZipIterator, PositiveOffset)
74+
{
75+
const std::string s{"oooo"}; // random access
76+
const std::string l{"bbbb"}; // random access
77+
78+
auto zip_itr_begin = mf::make_zip_iterator(s.begin(), l.begin());
79+
auto zip_itr_next = zip_itr_begin + 1;
80+
81+
ASSERT_EQ(std::distance(zip_itr_begin, zip_itr_next), 1);
82+
}
83+
84+
TEST(ZipIterator, NegativeOffset)
85+
{
86+
const std::string s{"oooo"}; // random access
87+
const std::string l{"bbbb"}; // random access
88+
89+
auto zip_itr_end = mf::make_zip_iterator(s.end(), l.end());
90+
auto zip_itr_prev = zip_itr_end - 1;
91+
92+
ASSERT_EQ(std::distance(zip_itr_end, zip_itr_prev), -1);
93+
}
94+
95+
TEST(ZipIterator, StdPrev)
96+
{
97+
const std::string s{"oooo"}; // random access
98+
const std::string l{"bbbb"}; // random access
99+
100+
auto zip_itr_end = mf::make_zip_iterator(s.end(), l.end());
101+
auto zip_itr_prev = std::prev(zip_itr_end);
102+
103+
ASSERT_EQ(std::distance(zip_itr_end, zip_itr_prev), -1);
104+
}

0 commit comments

Comments
 (0)