Skip to content

Instantly share code, notes, and snippets.

@maxgoren
Last active April 28, 2024 21:48
Show Gist options
  • Save maxgoren/3ff718cb2c1ff2570eb17021ec20d349 to your computer and use it in GitHub Desktop.
Save maxgoren/3ff718cb2c1ff2570eb17021ec20d349 to your computer and use it in GitHub Desktop.
a simplified version of std::deque
#ifndef simple_deque_hpp
#define simple_deque_hpp
template <class T>
class simple_deque_iterator;
template <class T>
class simple_deque {
private:
using iterator = simple_deque_iterator<T>;
using element_type = T;
using index = int;
element_type* data;
int max_capacity;
index first;
index last;
void grow() {
int i, j;
element_type* old = data;
data = new element_type[2*max_capacity];
first = (2*max_capacity)/4;
for (i = 0, j = (2*max_capacity)/4; i < max_capacity; i++, j++)
data[j] = old[i];
last = j;
max_capacity *= 2;
delete [] old;
}
public:
simple_deque() {
*this = simple_deque(8);
}
simple_deque(int capacity) {
max_capacity = capacity;
first = (max_capacity/2);
last = first;
data = new element_type[max_capacity];
}
simple_deque(const simple_deque& dq) {
}
~simple_deque() {
}
bool empty() const {
return size() == 0;
}
int size() const {
return last - first;
}
void push_front(element_type info) {
if (first == 0) {
if (max_capacity - last > 0) {
for (int i = last; i > 0; i--)
data[i] = data[i-1];
last++;
first++;
} else {
grow();
}
}
--first;
data[first] = info;
}
void push_back(element_type info) {
if (last == max_capacity) {
if (first > 0) {
for (int i = first-1; i < max_capacity; i++)
data[i] = data[i+1];
last--;
first--;
} else {
grow();
}
}
data[last++] = info;
}
element_type pop_front() {
return data[first++];
}
element_type pop_back() {
return data[--last];
}
void show() {
cout<<"[ ";
for (int i = 0; i < max_capacity; i++) {
if (i < first) cout<<" ";
else if (i > last) cout<<" ";
else {
cout<<data[i];
}
}
cout<<"]"<<endl;
}
iterator begin() {
return iterator(data+first);
}
iterator end() {
return iterator(data+last);
}
T& operator[](int index) {
return data[first+index];
}
};
template <class T>
class simple_deque_iterator {
private:
T* curr;
public:
simple_deque_iterator(T* position) {
curr = position;
}
T& operator*() {
return *curr;
}
simple_deque_iterator operator++() {
curr++;
return *this;
}
simple_deque_iterator operator++(int) {
++curr;
return *this;
}
simple_deque_iterator operator--() {
curr--;
return *this;
}
simple_deque_iterator operator--(int) {
--curr;
return *this;
}
bool operator==(const simple_deque_iterator& dqit) {
return curr == dqit.curr;
}
bool operator!=(const simple_deque_iterator& dqit) {
return !(*this==dqit);
}
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment