Vector: Add find() and some iterator improvements

Vector now has find() just like HashTable. I also made the iterator
comparison functions const-correct.
This commit is contained in:
Andreas Kling 2019-08-04 19:21:08 +02:00
parent 539985f4fe
commit 2a89bb2ac4

View file

@ -24,11 +24,11 @@ class Vector;
template<typename VectorType, typename ElementType>
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<typename Finder>
ConstIterator find(Finder finder) const
{
for (int i = 0; i < m_size; ++i) {
if (finder(at(i)))
return ConstIterator(*this, i);
}
return end();
}
template<typename Finder>
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()
{