Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Write a class template that uses a vector to implement a stack data structure.*/
- /*Modify your solution to the previous exercise so that the type of the container
- used to implement the stack is a template template parameter.*/
- #include <vector>
- #include <iostream>
- #include <stdexcept>
- using namespace std;
- template<class T, template<class U, class = allocator<U> > class Cont>
- class Stack {
- Cont<T> stack;
- public:
- void push(const T& t);
- void pop();
- const T& top();
- bool empty() { return stack.empty(); }
- };
- template<class T, template<class U, class = allocator<U> > class Cont>
- void Stack<T,Cont>::push(const T& t) {
- stack.push_back(t);
- }
- template<class T, template<class U, class = allocator<U> > class Cont>
- void Stack<T,Cont>::pop() {
- if (stack.empty() ) throw runtime_error("Stack empty");
- stack.erase(stack.end()-1, stack.end());
- }
- template<class T, template<class U, class = allocator<U> > class Cont>
- const T& Stack<T,Cont>::top() {
- if ( stack.empty() ) throw runtime_error("Stack empty");
- return *(stack.end()-1);
- }
- int main(int argc, char**argv)
- {
- Stack<int,vector> st;
- st. push(1);
- st.push(2);
- st. push(3);
- try {
- while (!st.empty()) {
- cout << st.top() << " ";
- st.pop();
- }
- } catch (std::runtime_error& e) {
- cout << e.what() << endl;
- }
- cout << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement