c++ - Is it possible to use inside a template class, a vector of class stack elements? -
i have "stack.h" , "stack.cpp" file define hand-made stack class.
what want now, create class "name" has in it's composition vector of "nr" stacks , i'm not sure start.
depou.h:
#pragma once #include <vector> #include "stiva.h" template <class t> class depou { private: int nr; std::vector<stiva<t> > depouarray; public: depou (int x, int lungtren); }; template <class t> depou<t>::depou (int x, int lungtren){ int i; nr = x; depouarray = new std::vector<stiva<t> > (nr); /* (i=0; i<nr; i++){ depouarray[i] = stiva<t> (lungtren); } incorrect */ }
my name.h doesn't compile want know if it's possible vector of kind.
my stack header called "stiva", edited "name.h" file according so.
stiva.h
#pragma once template <class t> class stiva { private: int top; int size; t *stackarray; public: stiva(); stiva (int s); ~stiva (){ delete [] stackarray; } int push (const t&); int pop (t&); int topelem (t&); int isempty (){return top == -1;} int isfull () {return top == size -1;} int search (t x); void setsize (const int& sz){ size=sz; } }; template <class t> stiva<t>::stiva (){ size = 10; top = -1; stackarray = new t[size]; } template <class t> stiva<t>::stiva (int s){ size = s>0 && s<1000? s : 10; top = -1; stackarray = new t[size]; } template <class t> int stiva<t>::push (const t& x){ if (!isfull()){ stackarray[++top] = x; return 1; } else{ size *= 2; stackarray = (t*) realloc (stackarray, 2*size * sizeof(t)); stackarray[++top] = x; return 1; } return 0; } template <class t> int stiva<t>::pop (t& popvalue){ if (!isempty ()){ popvalue = stackarray[top--]; return 1; } return 0; } template <class t> int stiva<t>::topelem (t& topvalue){ if (!isempty ()){ topvalue = stackarray[top]; return 1; } return 0; }
in main initialize this:
depou d(5,10);
you can initialize vector given size in member intializer of constructor:
template <class t> class name { private: int nr; std::vector<stack<t> > namearray; public: name (int x) : nr(x), namearray(nr) {} //other methods };
working example here: http://codepad.org/zt9iuqeg
Comments
Post a Comment