Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- class Item
- {
- string name;
- public:
- Item() {}
- Item(string name) { this->name = name; }
- };
- class Stack
- {
- protected:
- virtual void push(Item* obj) = 0;
- virtual void pop() = 0;
- virtual Item* get() = 0;
- };
- class ArrayStack : public Stack
- {
- int maxsize, size;
- Item* tab;
- public:
- ArrayStack(int maxsize)
- {
- if(maxsize<0) { throw "WrongSizeException"; }
- size = 0;
- this->maxsize = maxsize; tab = new Item[maxsize];
- }
- ~ArrayStack() { delete[] tab; };
- virtual void push(Item* obj) // umieszcza el na stosie
- {
- if(size == maxsize) { throw "StackFullException"; }
- else { tab[size] = *obj; size++; }
- }
- virtual void pop() // uswa el ze stosu
- {
- if(size == 0) { throw "StackEmptyException"; }
- else { size--; }
- }
- virtual Item* get() // zwraca el ze stosu
- {
- if(size == 0) { throw "StackEmptyException"; }
- else { return &tab[size]; }
- }
- };
- class DynamicArrayStack : public Stack
- {
- int maxsize, size;
- Item* tab;
- public:
- DynamicArrayStack(int starting_size = 0)
- {
- starting_size = maxsize;
- if(starting_size<0) { throw "WrongSizeException"; }
- size = 0;
- tab = new Item[starting_size];
- }
- virtual void push(Item* obj) // umieszcza el na stosie
- {
- if(size == maxsize)
- {
- Item *temp = tab;
- tab = new Item[maxsize*2];
- maxsize = maxsize*2;
- for(int i=0; i<maxsize/2; i++)
- {
- tab[i] = temp[i];
- }
- tab[size] = *obj; size++;
- }
- else
- {
- tab[size] = *obj; size++;
- }
- }
- virtual void pop() // uswa el ze stosu
- {
- if(size == 0) { throw "StackEmptyException"; }
- else { size--; }
- }
- virtual Item* get() // zwraca el ze stosu
- {
- if(size == 0) { throw "StackEmptyException"; }
- else { return &tab[size]; }
- }
- };
- int main()
- {
- Item sword("Excalibur");
- Item axe("Destroyer");
- try
- {
- DynamicArrayStack bag(3);
- bag.push(&sword);
- bag.push(&axe);
- bag.push(&axe);
- bag.push(&axe);
- bag.push(&axe);
- }
- catch(const char* e)
- {
- cout << e << endl; // gdy podany rozmiar stosu < 0
- }
- catch(const char* e)
- {
- cout << e << endl; // użytkownik usiłuje dodać element na pełen stos
- }
- catch(const char* e)
- {
- cout << e << endl; // użytkownik usiłuje pobrać lub usunąć element pustego stosu
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement