Skip to content

Instantly share code, notes, and snippets.

@lcarsos
Last active August 29, 2015 14:19
Show Gist options
  • Save lcarsos/63fb9dd08dc390379f14 to your computer and use it in GitHub Desktop.
Save lcarsos/63fb9dd08dc390379f14 to your computer and use it in GitHub Desktop.
C++ Fixed Size Circular Array
#ifndef CIRCULAR_H
#define CIRCULAR_H
/**
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <ezekiel@lcarsos.com> wrote this file. As long as you retain this notice
* you can do whatever you want with this stuff. If we meet some day, and you
* think this stuff is worth it, you can buy me a beer in return.
* Ezekiel Chopper
* ----------------------------------------------------------------------------
*/
/**
* Circular is a circular array using stack space. It allows for native
* indexing (using negative integers to go "backwards"). It is extremely
* feature sparse.
*/
template<typename T, unsigned long long N>
class circular {
public:
const unsigned long long length = N;
T& operator[](long long i) {
unsigned long long index = i < 0 ? N + i : i;
return m_array[index % N];
}
const T& operator[](long long i) const {
unsigned long long index = i < 0 ? N + i : i;
return m_array[index % N];
}
private:
T m_array[N];
};
#endif // CIRCULAR_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment