Skip to content

Instantly share code, notes, and snippets.

@Battleroid
Last active December 14, 2015 11:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Battleroid/5081861 to your computer and use it in GitHub Desktop.
Save Battleroid/5081861 to your computer and use it in GitHub Desktop.
Thing to create a 'stack' class that accepts any kind of type for input using vectors instead of arrays per class exercise. For whatever reason doesn't work in VS2012 but compiles online just fine (using the same compiler, go figure). Whatever.
#include <iostream>
#include "Stack.h"
using namespace std;
int main () {
Stack<int> s1;
Stack<double> s2;
for (int i = 0; i < 5; i++)
{
int value;
cout << "Enter a value: ";
cin >> value;
s1.push(value);
s2.push(value * 5.5 * i);
}
while (!s1.empty())
{
cout << s1.pop() + s2.pop() << endl;
}
system("pause");
return 0;
}
#ifndef STACK_H
#define STACK_H
#include <vector>
template<typename T>
class Stack {
public:
Stack();
void push(T const&);
T pop();
bool empty() const;
private:
std::vector<T> elems;
};
template<typename T>
Stack<T>::Stack() {
std::vector<T> elems;
}
template<typename T>
void Stack<T>::push(T const& element) {
elems.push_back(element);
}
template<typename T>
T Stack<T>::pop() {
elems.pop_back();
return elems[elems.size()];
}
template<typename T>
bool Stack<T>::empty() const {
return elems.empty();
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment