Skip to content

Instantly share code, notes, and snippets.

@acgetchell
Last active February 15, 2020 21:01
Show Gist options
  • Save acgetchell/7d90de3c79516cbe0e2e69ed8cca07a5 to your computer and use it in GitHub Desktop.
Save acgetchell/7d90de3c79516cbe0e2e69ed8cca07a5 to your computer and use it in GitHub Desktop.
Adding iterators to a class for use in ranged-for loops. See https://godbolt.org/z/4FLhuY
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Ring
{
private:
int m_size;
T* m_data;
int m_pos;
public:
Ring(int const t_size) : m_size{t_size}, m_data{ new T[m_size]}, m_pos{0} {}
~Ring() {
delete [] m_data;
cout << "Destructed." << endl;
}
void add(T const t_arg) {
m_data[m_pos++] = t_arg;
if (m_pos == m_size) m_pos = 0;
}
int size() const { return m_size; }
T& get(int const t_index) const { return m_data[t_index]; }
class iterator;
iterator begin() {
return iterator(0, *this);
}
iterator end() {
return iterator(m_size, *this);
}
};
template <typename T>
class Ring<T>::iterator
{
private:
int m_pos;
Ring& m_ring;
public:
iterator(int t_pos, Ring& t_ring) : m_pos{t_pos}, m_ring{t_ring} {}
bool operator!=(iterator const& t_other) const { return m_pos != t_other.m_pos; }
// Postfix ++
iterator& operator++(int) {
m_pos++;
return *this;
}
// Prefix ++, required for C++ 11 style ranged-for
iterator& operator++() {
m_pos++;
return *this;
}
// Postfix --
iterator& operator--(int) {
m_pos--;
return *this;
}
T& operator*() { return m_ring.get(m_pos); }
};
int main() {
Ring<string> textring(3);
textring.add("one");
textring.add("two");
textring.add("three");
// Output one, two, three
for(int i = 0; i < textring.size(); i++) {
cout << textring.get(i) << endl;
}
cout << endl;
textring.add("four");
textring.add("five");
// Output four, five, three
// C++ 98 style
for(Ring<string>::iterator it = textring.begin(); it != textring.end(); it++) {
cout << *it << endl;
}
cout << endl;
auto end = textring.end();
*end-- = "six";
// Output four, five, six
// C++ 11 style
for (auto value: textring) {
cout << value << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment