Skip to content

Instantly share code, notes, and snippets.

@odarbelaeze
Last active October 11, 2020 17:52
Show Gist options
  • Save odarbelaeze/5378890 to your computer and use it in GitHub Desktop.
Save odarbelaeze/5378890 to your computer and use it in GitHub Desktop.
A FIFO Stack implementation using a simple array.
#include <iostream>
#include <exception>
#include <stdexcept>
#include <functional>
#include <string>
// 1234--------
template<typename T>
class QeueArray
{
public:
QeueArray()
{
allocated_ = 1;
N_ = 0;
data_ = new T[allocated_];
}
void push_back(T item)
{
if (N_ == allocated_)
{
T* copy = data_;
allocated_ *= 2;
data_ = new T[allocated_];
for (int i = 0; i < N_; ++i)
data_[i] = copy[i];
}
data_[N_++] = item;
}
T pop_back()
{
if (N_ == 0) throw std::out_of_range("The queue is actually empty.");
if (N_ == allocated_ / 4)
{
T* copy = data_;
allocated_ /= 2;
data_ = new T[allocated_];
for (int i = 0; i < N_; ++i)
data_[i] = copy[i];
}
return data_[--N_];
}
size_t size()
{
return N_;
}
T operator[] (int i)
{
return data_[i];
}
private:
T* data_;
size_t allocated_;
size_t N_;
};
int main(int argc, char const *argv[])
{
QeueArray<int> q;
for (int i = 0; i < 200000000; i++)
q.push_back(2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment