Skip to content

Commit

Permalink
Add ConstIterator for HeightMap
Browse files Browse the repository at this point in the history
  • Loading branch information
dxrcy committed Dec 3, 2024
1 parent 04eeecc commit 1ca0568
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions include/mcpp/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -435,8 +435,101 @@ struct HeightMap {
pointer m_ptr;
};

/**
* @brief An iterator for the const HeightMap structure.
*
* This iterator allows for range-based for loops and standard const
* iterator operations over the height data stored within a HeightMap.
*/
struct ConstIterator {
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = int;
using pointer = const int*;
using reference = const int&;

/**
* @brief Constructs an iterator at the given pointer position.
*
* @param ptr Pointer to the position in the height array.
*/
ConstIterator(pointer ptr) : m_ptr(ptr) {}

/**
* @brief Dereference the iterator to access the value at the current
* position.
*
* @return Reference to the current element.
*/
reference operator*() const { return *m_ptr; }

/**
* @brief Access the pointer to the current element.
*
* @return Pointer to the current element.
*/
pointer operator->() { return m_ptr; }

/**
* @brief Pre-increment operator. Advances the iterator to the next
* position.
*
* @return Reference to the updated iterator.
*/
ConstIterator& operator++() {
m_ptr++;
return *this;
}

/**
* @brief Post-increment operator. Advances the iterator to the next
* position.
*
* @param int Unused dummy parameter to differentiate from prefix
* increment.
* @return Iterator to the original position before incrementing.
*/
ConstIterator operator++(int) {
ConstIterator tmp = *this;
++(*this);
return tmp;
}

/**
* @brief Equality comparison operator.
*
* @param a First iterator to compare.
* @param b Second iterator to compare.
* @return true if both iterators point to the same position, false
* otherwise.
*/
friend bool operator==(const ConstIterator& a, const ConstIterator& b) {
return a.m_ptr == b.m_ptr;
};

/**
* @brief Inequality comparison operator.
*
* @param a First iterator to compare.
* @param b Second iterator to compare.
* @return true if iterators point to different positions, false
* otherwise.
*/
friend bool operator!=(const ConstIterator& a, const ConstIterator& b) {
return a.m_ptr != b.m_ptr;
};

private:
pointer m_ptr;
};

Iterator begin() { return Iterator(&raw_heights[0]); }
Iterator end() { return Iterator(&raw_heights[_x_len * _z_len]); }
ConstIterator begin() const { return ConstIterator(&raw_heights[0]); }
ConstIterator end() const {
return ConstIterator(&raw_heights[_x_len * _z_len]);
}

HeightMap(const Coordinate& loc1, const Coordinate& loc2,
const std::vector<int>& heights);

Expand Down

0 comments on commit 1ca0568

Please sign in to comment.