Last active
December 14, 2015 11:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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