daily pastebin goal
43%
SHARE
TWEET

Untitled

a guest Jun 13th, 2018 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Ring.h
  2. #ifndef RING.H
  3. #define RING.H
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. template<class T>
  8. class ring {
  9.     unsigned int m_size;
  10.     int m_pos;
  11.     T *m_values;
  12. public:
  13.     class iterator;
  14. public:
  15.     ring(unsigned int size) : m_size(size), m_pos(0)
  16.     {
  17.         m_values = new T[m_size];
  18.     }
  19.     ~ring()
  20.     {
  21.         delete[] m_values;
  22.     }
  23.     void add(const T &val)
  24.     {
  25.         m_values[m_pos] = val;
  26.         m_pos++;
  27.         m_pos %= m_size;
  28.     }
  29.     T& get(int pos)
  30.     {
  31.         return m_values[pos];
  32.     }
  33.     iterator begin()
  34.     {
  35.         return iterator(0, *this);
  36.     }
  37.     iterator end()
  38.     {
  39.         return iterator(m_size, *this);
  40.     }
  41. };
  42. template<class T>
  43. class ring<T>::iterator {
  44.     int m_pos;
  45.     ring &m_ring;                              // Removing & gives garbage output.
  46. public:
  47.     iterator(int pos, ring& aRing) : m_pos(pos), m_ring(aRing){}
  48.     bool operator!=(const iterator &other) const
  49.     {
  50.         return other.m_pos != m_pos;
  51.     }
  52.     iterator &operator++(int)
  53.     {
  54.         m_pos++;
  55.         return *this;
  56.     }
  57.     iterator &operator++()
  58.     {
  59.         m_pos++;
  60.         return *this;
  61.     }
  62.     T &operator*()
  63.     {
  64.        // return m_ring.m_values[m_pos];
  65.         return m_ring.get(m_pos);
  66.     }
  67. };
  68. #endif // RING
  69.    
  70. // Ring_Buffer_Class.cpp
  71.  
  72. #include <iostream>
  73. #include "ring.h"
  74. using namespace std;
  75. int main()
  76. {
  77.     ring<string> textring(3);
  78.     textring.add("one");
  79.     textring.add("two");
  80.     textring.add("three");
  81.     textring.add("four");
  82.     // C++ 98
  83.     for(ring<string>::iterator it = textring.begin(); it != textring.end(); it++)
  84.     {
  85.         cout << *it << endl;
  86.     }
  87.     cout << endl;
  88.     // C++11
  89.     for(string value : textring)
  90.     {
  91.         cout << value << endl;
  92.     }
  93.     return 0;
  94. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top