Skip to content

Commit

Permalink
Add iterator for sparse set
Browse files Browse the repository at this point in the history
  • Loading branch information
FigBug committed Dec 28, 2024
1 parent 29e6bee commit 5a98881
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions modules/juce_core/containers/juce_SparseSet.h
Original file line number Diff line number Diff line change
Expand Up @@ -277,4 +277,69 @@ class SparseSet
}
};

//==============================================================================
/** Iterator for a SparseSet.
You shouldn't ever need to use this class directly - it's used internally by begin()
and end() to allow range-based-for loops on a SparseSet.
*/
template <class Type>
struct SparseSetIterator
{
SparseSetIterator (const SparseSet<Type>& s, bool isEnd)
: set (s)
{
if (isEnd)
rangeIndex = set.getRanges().size();
}

SparseSetIterator& operator++()
{
valueIndex++;
if (valueIndex == set.getRanges()[rangeIndex].getLength())
{
rangeIndex++;
valueIndex = 0;
}
return *this;
}

bool operator== (const SparseSetIterator<Type>& other) const
{
return rangeIndex == other.rangeIndex && valueIndex == other.valueIndex;
}

bool operator!= (const SparseSetIterator<Type>& other) const
{
return ! (*this == other);
}

Type operator*() const
{
return set.getRanges()[rangeIndex].getStart() + valueIndex;
}

using difference_type = std::ptrdiff_t;
using value_type = Type;
using reference = Type&;
using pointer = Type*;
using iterator_category = std::forward_iterator_tag;

private:
const SparseSet<Type>& set;
int rangeIndex = 0;
int valueIndex = 0;
};

template <class Type>
SparseSetIterator<Type> begin (const SparseSet<Type>& ss)
{
return SparseSetIterator<Type> (ss, false);
}

template <class Type>
SparseSetIterator<Type> end (const SparseSet<Type>& ss)
{
return SparseSetIterator<Type> (ss, true);
}

} // namespace juce

0 comments on commit 5a98881

Please sign in to comment.