Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- template <typename Type>
- class Stack {
- private:
- Type* mData;
- int mSize;
- int mTop;
- public:
- Stack(int size) : mSize(size) {
- mTop = -1;
- mData = new Type[mSize];
- }
- Stack(const Stack& ref) {
- mTop = ref.mTop;
- mSize = ref.mSize;
- mData = new Type[mSize];
- for (int i = 0; i < mSize; i++) {
- mData[i] = ref.mData[i];
- }
- }
- ~Stack() {
- delete[] mData;
- }
- Type& operator[](int idx) {
- return mData[idx];
- }
- Stack& operator=(const Stack& ref) {
- if (this != &ref) {
- mSize = ref.mSize;
- mData = new Type[mSize];
- for (int i = 0; i < mSize; i++) {
- mData[i] = ref.mData[i];
- }
- }
- return *this;
- }
- bool push(const Type& x) {
- if (mTop >= (mSize - 1)) {
- cout << "Stack Overflow";
- return false;
- }
- else {
- mData[++mTop] = x;
- cout << x << " pushed into stack\n";
- return true;
- }
- }
- Type pop() {
- if (mTop < 0) {
- cout << "Stack Underflow";
- return 0;
- }
- else {
- Type x = mData[mTop--];
- return x;
- }
- }
- void top() {
- cout << mData[mTop] << endl;
- }
- };
- int main() {
- Stack<int> first(10);
- Stack<double> second(7);
- Stack<int> third = first;
- std::srand((unsigned int)time(0));
- for (int i = 0; i < 10; i++) {
- int random = (int)rand() * 10 / (int)RAND_MAX;
- first.push(random);
- }
- cout << first.pop() << endl;
- first.top();
- for (int i = 0; i < 7; i++) {
- double random = (double)rand() * 10 / (double)RAND_MAX;
- second.push(random);
- }
- cout << second.pop() << endl;
- second.top();
- for (int i = 0; i < 10; i++) {
- int random = (int)rand() * 10 / (int)RAND_MAX;
- third.push(random);
- }
- cout << third.pop() << endl;
- third.top();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement