From 2a89bb2ac48b7f641d3988f30baa3f5f98480199 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 4 Aug 2019 19:21:08 +0200 Subject: Vector: Add find() and some iterator improvements Vector now has find() just like HashTable. I also made the iterator comparison functions const-correct. --- AK/Vector.h | 42 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) (limited to 'AK') diff --git a/AK/Vector.h b/AK/Vector.h index 13592d017f..554da28431 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -24,11 +24,11 @@ class Vector; template class VectorIterator { public: - bool operator!=(const VectorIterator& other) { return m_index != other.m_index; } - bool operator==(const VectorIterator& other) { return m_index == other.m_index; } - bool operator<(const VectorIterator& other) { return m_index < other.m_index; } - bool operator>(const VectorIterator& other) { return m_index > other.m_index; } - bool operator>=(const VectorIterator& other) { return m_index >= other.m_index; } + bool operator!=(const VectorIterator& other) const { return m_index != other.m_index; } + bool operator==(const VectorIterator& other) const { return m_index == other.m_index; } + bool operator<(const VectorIterator& other) const { return m_index < other.m_index; } + bool operator>(const VectorIterator& other) const { return m_index > other.m_index; } + bool operator>=(const VectorIterator& other) const { return m_index >= other.m_index; } VectorIterator& operator++() { ++m_index; @@ -49,6 +49,8 @@ public: ElementType& operator*() { return m_vector[m_index]; } int operator-(const VectorIterator& other) { return m_index - other.m_index; } + bool is_end() const { return m_index == m_vector.size(); } + private: friend VectorType; VectorIterator(VectorType& vector, int index) @@ -450,6 +452,36 @@ public: ConstIterator begin() const { return ConstIterator(*this, 0); } ConstIterator end() const { return ConstIterator(*this, size()); } + template + ConstIterator find(Finder finder) const + { + for (int i = 0; i < m_size; ++i) { + if (finder(at(i))) + return ConstIterator(*this, i); + } + return end(); + } + + template + Iterator find(Finder finder) + { + for (int i = 0; i < m_size; ++i) { + if (finder(at(i))) + return Iterator(*this, i); + } + return end(); + } + + ConstIterator find(const T& value) const + { + return find([&](auto& other) { return value == other; }); + } + + Iterator find(const T& value) + { + return find([&](auto& other) { return value == other; }); + } + private: void reset_capacity() { -- cgit v1.2.3