Created
September 15, 2016 15:36
-
-
Save itayB/bfa8129ec248f9611da2eb40c31dd773 to your computer and use it in GitHub Desktop.
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
| #include <iostream> | |
| #include <stdexcept> | |
| using namespace std; | |
| template <class T> class CircularArray { | |
| private: | |
| int size; | |
| int head; | |
| T* arr; | |
| int convert(int i) { | |
| return (head + i) % size; | |
| } | |
| public: | |
| /* Constructor */ | |
| CircularArray(int size) { | |
| if (size <= 0) | |
| throw std::invalid_argument( "illegal value" ); | |
| arr = new T[size]; | |
| head = 0; | |
| this->size = size; | |
| } | |
| /* Destructor */ | |
| virtual ~CircularArray() { | |
| delete arr; | |
| } | |
| void shift(int shiftRight) { | |
| // TODO: neg input | |
| head = (head + shiftRight) % size; | |
| } | |
| T get(int i) { | |
| if (i < 0 || i >= size) | |
| throw std::invalid_argument( "illegal value" ); | |
| return arr[convert(i)]; | |
| } | |
| void set(int i, T t) { | |
| if (i < 0 || i >= size) | |
| throw std::invalid_argument( "illegal value" ); | |
| arr[convert(i)] = t; | |
| } | |
| void print() { | |
| cout << "["; | |
| for (int i=0 ; i < size ; i++) { | |
| if (i) | |
| cout << ", "; | |
| cout << this->get(i); | |
| } | |
| cout << "]" << endl; | |
| } | |
| }; | |
| int main() { | |
| int n = 10; | |
| CircularArray<int> cArr(n); | |
| // fill array | |
| for (int i=0 ; i < n ; i++) { | |
| cArr.set(i,i+1); | |
| } | |
| cArr.print(); | |
| cArr.shift(3); | |
| cArr.print(); | |
| cArr.shift(2); | |
| cArr.print(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment