Last active
October 11, 2020 17:52
-
-
Save odarbelaeze/5378890 to your computer and use it in GitHub Desktop.
A FIFO Stack implementation using a simple array.
This file contains 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 <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