Advertisement
amarek

OOP LV4 - Zadatak2

Nov 11th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4.  
  5. using namespace std;
  6.  
  7. template <typename Type>
  8. class Stack {
  9. private:
  10.     Type* mData;
  11.     int mSize;
  12.     int mTop;
  13. public:
  14.     Stack(int size) : mSize(size) {
  15.         mTop = -1;
  16.         mData = new Type[mSize];
  17.     }
  18.  
  19.     Stack(const Stack& ref) {
  20.         mTop = ref.mTop;
  21.         mSize = ref.mSize;
  22.         mData = new Type[mSize];
  23.         for (int i = 0; i < mSize; i++) {
  24.             mData[i] = ref.mData[i];
  25.         }
  26.     }
  27.  
  28.     ~Stack() {
  29.         delete[] mData;
  30.     }
  31.  
  32.     Type& operator[](int idx) {
  33.         return mData[idx];
  34.     }
  35.  
  36.     Stack& operator=(const Stack& ref) {
  37.         if (this != &ref) {
  38.             mSize = ref.mSize;
  39.             mData = new Type[mSize];
  40.             for (int i = 0; i < mSize; i++) {
  41.                 mData[i] = ref.mData[i];
  42.             }
  43.         }
  44.         return *this;
  45.     }
  46.  
  47.     bool push(const Type& x) {
  48.         if (mTop >= (mSize - 1)) {
  49.             cout << "Stack Overflow";
  50.             return false;
  51.         }
  52.         else {
  53.             mData[++mTop] = x;
  54.             cout << x << " pushed into stack\n";
  55.             return true;
  56.         }
  57.     }
  58.  
  59.     Type pop() {
  60.         if (mTop < 0) {
  61.             cout << "Stack Underflow";
  62.             return 0;
  63.         }
  64.         else {
  65.             Type x = mData[mTop--];
  66.             return x;
  67.         }
  68.     }
  69.  
  70.     void top() {
  71.         cout << mData[mTop] << endl;
  72.     }
  73. };
  74.  
  75.  
  76. int main() {
  77.     Stack<int> first(10);
  78.     Stack<double> second(7);
  79.     Stack<int> third = first;
  80.     std::srand((unsigned int)time(0));
  81.     for (int i = 0; i < 10; i++) {
  82.         int random = (int)rand() * 10 / (int)RAND_MAX;
  83.         first.push(random);
  84.     }
  85.     cout << first.pop() << endl;
  86.     first.top();
  87.  
  88.     for (int i = 0; i < 7; i++) {
  89.         double random = (double)rand() * 10 / (double)RAND_MAX;
  90.         second.push(random);
  91.     }
  92.     cout << second.pop() << endl;
  93.     second.top();
  94.  
  95.     for (int i = 0; i < 10; i++) {
  96.         int random = (int)rand() * 10 / (int)RAND_MAX;
  97.         third.push(random);
  98.     }
  99.     cout << third.pop() << endl;
  100.     third.top();
  101.  
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement