Please review my simple Stack
:
template<class T>
class Stack {
public:
Stack() = default;
Stack(std::initializer_list<T> i) :n{} {
for (auto& x : i) {
elem.push_back(x);
++n;
}
}
Stack(const Stack<T>&) = default;
Stack(Stack<T>&&) = default;
Stack& operator=(const Stack&) = default;
Stack& operator=(Stack&&) = default;
~Stack() = default;
int size() const {
return n;
}
bool isEmpty() const {
return (n == 0);
}
void push(T);
T pop();
T& peek();
private:
std::vector<T> elem;
int n;
};
template<class T>
void Stack<T>::push(T t) {
elem.push_back(t);
++n;
}
template<class T>
T Stack<T>::pop() {
if (isEmpty()) {
throw std::out_of_range("underflow");
}
T t = *elem.erase(elem.end()-1);
--n;
return t;
}
template<class T>
T& Stack<T>::peek() {
if (isEmpty()) {
throw std::out_of_range("underflow");
}
return elem[n-1];
}
How can I make this code better and build more complicated data structures based on stacks?
std::stack
? – John Dibling Nov 10 '14 at 17:43