Implementation of the class template stack
Stack1.hpp#include<vector> #include <stdexcept>using namespace std;template <typename T>class stack{private:vector<t> elems;public:void push (T const&); void pop (); T top () const;bool empty () Const{return elems.empty ();}}; Template <typename t>void stack<t>::p ush (T const &elem) {elems.push_back (elem);//vector the last one added, That is, add an element to the top of the stack}template <typename t>void stack<t>::p op () {if (Elems.empty ()) {throw Out_of_range ("stack< ::p op (): Empty stack "); Elems.pop_back ();//vector remove the last element, that is, remove the top element of the stack}template <typename t>t stack<t>::top () const{if ( Elems.empty ()) {throw Out_of_range ("Stack<>::top (): Empty Stack");} return Elems.back ();//vector inside returns the last element, the stack top element inside the stack}
As you can see, the class template stack<> is implemented through the class template vector<> of the C + + standard library, so we do not need to implement memory management, copy constructors and assignment operators in person, so that we can focus on the interface implementation of the template class.
main.cpp//class template Stack implementation #include<iostream> #include <string> #include <vector> #include "stack1.hpp" Using namespace Std;int main () {stack<int> intstack;//use int buyers cout<< "Use int buyers" <<endl;for (int i=1; i<6;i++) Intstack.push (i); while (!intstack.empty ()) {cout<<intstack.top () << ""; Intstack.pop (); cout<<endl; stack<string> stringstack;cout<< "Please enter string (#退出):"; string Str;while (Cin>>str) {if (str== "#") break ; Stringstack.push (str);} while (!stringstack.empty ()) {cout<<stringstack.top () << ""; Stringstack.pop ();} Cout<<endl;system ("pause"); return 0;}
By declaring the type Stack<int>, you can instantiate T with int inside the class template, so Intsatck is an object that is created from Stack<int>, whose elements are stored in the vector and are int.
For all called member functions, a function code based on the int type is instantiated.
Note: Only those member functions that are called will produce instantiation code for these functions. For a class template, member functions are instantiated only when they are used.
Implementation of C + + template--class template stack