C++ (Pop in Array Based Stack) Do we delete the element? -


here code lecture note stack using array implementation.

in specification:

template <typename t> class stack { public:     stack();     bool pop (t& stacktop);     //there still other code  private:     int maxsize;     int* arr;     int _size; } 

in implementation:

bool stack<t>::pop(t& stacktop){     if (isempty()){          return false;     }else{         --_size;         stacktop=arr[_size];         return true;     } } 

and example of user program:

stack<int> st; int k; st.push(1);st.push(2);st.push(3);//will add element 1 ,2, , 3. st.pop(k);cout<<"pop"<<k<<endl; //will pop last element 3 , print pop 3 

i understand in pop implementation , update( reduce one) size of array. don't seem erase element! so, element still there, , reduce size top of array shifted? e.g. maximum size 100 in code push 1, 2 , 3. top on 3. , rest 97 elements still unassigned. pop (which last element 3). when pop, "move" top 2. 3 still there, , rest 97 elements still unassigned. ???

please explain how works.

popping element should remove stack @ same time return same element (whether delete or process further you).

in case use static structure such array stack can nullify content of cell represented stack's top have popped, return element (if store value, return otherwise return reference) , set index element underneath new top or create copy of array smaller size , copy content has not been popped there. can optimize last method trying popping in batch multiple poppings 1 after , "flush" stack newer smaller one. prefer first way since stack considered size (=a stack bounded instead of dynamic capacity).

removing element when popping way pop in stack works , if leave old value there might example lead dumb situation overwriting element, have popped push command didn't want overwrite @ all. if proper way know once popped value can no longer retrieved (except @ moment of popping it) stack because no longer there!

also can use single linked list implementation , can indeed reduce size of stack when doing pop , not "replace" popped element dummy value or create new smaller stack , copy rest there.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -