Created
April 5, 2020 08:42
-
-
Save jhurliman/58b9ee8f52053a0e3dbbb45aad718457 to your computer and use it in GitHub Desktop.
CircularArray - Wraps std::array and provides a circular iterator in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <algorithm> | |
#include <array> | |
template <class T, size_t N> | |
class CircularArray { | |
public: | |
CircularArray() {} | |
CircularArray(const T initValue) { std::fill_n(data_.begin(), data_.size(), initValue); } | |
T at(size_t n) { return data_.at(n); } | |
std::array<T, N> &data() const { return data_; } | |
size_t size() { return v.size(); } | |
class iterator : public std::iterator<std::random_access_iterator_tag, T> { | |
CircularArray *array; | |
ssize_t index; | |
public: | |
iterator(CircularArray &d, ssize_t idx) | |
: array(&d) | |
, index(idx) {} | |
iterator &operator++() { | |
nextIndex(); | |
return *this; | |
} | |
iterator operator++(ssize_t) { | |
iterator tmp(*array, index); | |
nextIndex(); | |
return tmp; | |
} | |
iterator operator+(ssize_t off) { return iterator(*array, (index + off) % array->size()); } | |
iterator operator-(ssize_t off) { | |
return iterator(*array, (index - off + array->size()) % array->size()); | |
} | |
T &operator*() { return (*array).data_[index]; } | |
bool operator!=(iterator const &other) { return index != other.index; } | |
private: | |
void nextIndex() { | |
++index; | |
if (index == array->size()) { | |
index = 0; | |
} | |
} | |
}; | |
iterator begin() { return iterator(*this, 0); } | |
private: | |
std::array<T, N> data_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment