[ADT] add pointer_iterator, the opposite of pointee_iterator

Differential Revision: https://reviews.llvm.org/D23703

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@279323 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Tim Shen 2016-08-19 21:04:45 +00:00
parent 47b194388e
commit 878c720c8a
2 changed files with 41 additions and 0 deletions

View File

@ -256,6 +256,23 @@ struct pointee_iterator
T &operator*() const { return **this->I; }
};
template <typename WrappedIteratorT,
typename T = decltype(&*std::declval<WrappedIteratorT>())>
class pointer_iterator
: public iterator_adaptor_base<pointer_iterator<WrappedIteratorT>,
WrappedIteratorT, T> {
mutable T Ptr;
public:
pointer_iterator() {}
explicit pointer_iterator(WrappedIteratorT u)
: pointer_iterator::iterator_adaptor_base(std::move(u)) {}
T &operator*() { return Ptr = &*this->I; }
const T &operator*() const { return Ptr = &*this->I; }
};
}
#endif

View File

@ -185,4 +185,28 @@ TEST(FilterIteratorTest, InputIterator) {
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(PointerIterator, Basic) {
int A[] = {1, 2, 3, 4};
pointer_iterator<int *> Begin(std::begin(A)), End(std::end(A));
EXPECT_EQ(A, *Begin);
++Begin;
EXPECT_EQ(A + 1, *Begin);
++Begin;
EXPECT_EQ(A + 2, *Begin);
++Begin;
EXPECT_EQ(A + 3, *Begin);
++Begin;
EXPECT_EQ(Begin, End);
}
TEST(PointerIterator, Const) {
int A[] = {1, 2, 3, 4};
const pointer_iterator<int *> Begin(std::begin(A));
EXPECT_EQ(A, *Begin);
EXPECT_EQ(A + 1, std::next(*Begin, 1));
EXPECT_EQ(A + 2, std::next(*Begin, 2));
EXPECT_EQ(A + 3, std::next(*Begin, 3));
EXPECT_EQ(A + 4, std::next(*Begin, 4));
}
} // anonymous namespace