Skip to content

Instantly share code, notes, and snippets.

@sappho192
Created April 7, 2017 15:16
Show Gist options
  • Save sappho192/1dd9f9edf07d01f6da367616edd8ab01 to your computer and use it in GitHub Desktop.
Save sappho192/1dd9f9edf07d01f6da367616edd8ab01 to your computer and use it in GitHub Desktop.
[C++] ArrayStack written in template
#pragma once
#ifndef ARRAYSTACK_H
#define ARRAYSTACK_H
#include "StackEmptyException.h"
template <typename Object>
class ArrayStack
{
public:
ArrayStack(int c = MAX)
{
capacity = c;
elem = new Object[capacity];
top = -1;
}
ArrayStack(const ArrayStack &ss)
{
capacity = ss.capacity;
elem = new Object[ss.capacity];
top = ss.top;
for (int i = 0; i <= top; i++)
elem[i] = ss.elem[i];
}
void operator=(const ArrayStack &ss)
{
if (this == &ss)
return;
delete[] this->elem;
capacity = ss.capacity;
elem = new Object[ss.capacity];
top = ss.top;
for (int i = 0; i <= top; i++)
elem[i] = ss.elem[i];
}
int size() const
{
return top + 1;
}
bool isEmpty() const
{
return (top < 0);
}
void push(const Object &e)
{
if (size() == capacity)
{
Object * newElem = new Object[size() * 2];
capacity = size() * 2;
for (int i = 0; i < size(); i++)
newElem[i] = elem[i];
delete[] elem;
elem = newElem;
}
elem[++top] = e;
}
Object pop() throw (StackEmptyException)
{
try
{
if (isEmpty()) {
throw StackEmptyException("없음");
}
else {
return elem[top--];
}
}
catch (StackEmptyException ex)
{
ex.printerr();
//return 0; // ??
}
}
Object& topf()
{
try
{
if (isEmpty())
throw StackEmptyException("없음");
}
catch (StackEmptyException ex)
{
ex.printerr();
}
return elem[top];
}
private:
int top;
Object *elem;
int capacity;
enum { MAX = 1000 };
};
#endif
#include <iostream>
using std::cout;
using std::endl;
#include "ArrayStack.h"
int main()
{
ArrayStack <int> myS1(1);
for (int i = 0; i < 10; i++)
{
myS1.push(i);
cout << myS1.topf();
cout << " ";
cout << myS1.size();
cout << endl;
}
int end = myS1.size();
for (int i = 0;i< end + 1;i++)
{
cout << myS1.pop() << " ";
}
return 0;
}
#pragma once
#ifndef STACKEMPTYEXCEPTION_H
#define STACKEMPTYEXCEPTION_H
#include <iostream>
#include <string>
using namespace std;
class StackEmptyException
{
public:
StackEmptyException(string e)
{
exp = e;
}
void printerr()
{
cout << exp << endl;
}
private:
string exp;
};
#endif
@sappho192
Copy link
Author

Template code with strange case. Check line 76 of ArrayStack.h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment