템플릿을 이용해 간단한 스택을 구현했다.
/*
스택 구현
*/
#include <iostream>
#include <vector>
template <typename T>
class Stack
{
public:
void push(T const& elem);
void pop();
T top();
bool empty();
private:
std::vector<T> vector;
};
template <typename T>
void Stack<T>::push(T const& elem)
{
vector.push_back(elem);
}
template <typename T>
void Stack<T>::pop()
{
if (vector.empty()) {
throw std::out_of_range("Stack<>::pop() : empty stack");
}
vector.pop_back();
}
template <typename T>
T Stack<T>::top()
{
if (vector.empty()) {
throw std::out_of_range("Stack<>::pop() : empty stack");
}
return vector.back();
}
template <typename T>
bool Stack<T>::empty()
{
return vector.empty();
}
int main()
{
Stack<int> stack;
stack.push(1);
stack.push(2);
stack.pop();
std::cout << stack.top() << std::endl; // 출력 : 1
return 0;
}
반응형