From c7a797b9669b3c9cd42b9e9989b0c19428412ec2 Mon Sep 17 00:00:00 2001 From: Vladimir Glavnyy <31897320+vglavnyy@users.noreply.github.com> Date: Tue, 5 Jun 2018 02:02:08 +0700 Subject: [PATCH] Makes VectorIterator compatible with STL iterators. (#4768) --- include/flatbuffers/flatbuffers.h | 4 ++-- tests/test.cpp | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 107dc250e..b76b8a604 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -91,7 +91,7 @@ template struct IndirectHelper { template struct VectorIterator { typedef std::random_access_iterator_tag iterator_category; typedef IT value_type; - typedef uoffset_t difference_type; + typedef ptrdiff_t difference_type; typedef IT *pointer; typedef IT &reference; @@ -121,7 +121,7 @@ template struct VectorIterator { return data_ != other.data_; } - ptrdiff_t operator-(const VectorIterator &other) const { + difference_type operator-(const VectorIterator &other) const { return (data_ - other.data_) / IndirectHelper::element_stride; } diff --git a/tests/test.cpp b/tests/test.cpp index af0699ce8..4bd85988e 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -273,8 +273,13 @@ void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length, TEST_EQ(VectorLength(inventory), 10UL); // Works even if inventory is null. TEST_NOTNULL(inventory); unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - for (auto it = inventory->begin(); it != inventory->end(); ++it) - TEST_EQ(*it, inv_data[it - inventory->begin()]); + // Check compatibilty of iterators with STL. + std::vector inv_vec(inventory->begin(), inventory->end()); + for (auto it = inventory->begin(); it != inventory->end(); ++it) { + auto indx = it - inventory->begin(); + TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check. + TEST_EQ(*it, inv_data[indx]); + } TEST_EQ(monster->color(), Color_Blue);