简体   繁体   中英

template class & vector

Implement a template class named MyStack that creates a stack using STL class vector. MyStack class will have two functions – push() and pop(). Since MyStack is a template class, it must be written in such a way that it can be used to create stack of any type of data (both built-in and custom type). When an element of the stack is popped, it should be deleted from the vector so that the popped data does not use memory any more. In main(), create more than one such stack of different data types, push some sample data, and show the data when they are popped from the respective stack.

The only way to get a std::vector to shrink is to swap it with a smaller vector. So, freeing the memory of each object as it is popped entails copying (almost) the entire vector for every pop , making it an O(n) operation.

So, I recommend you don't do things that way, or if this is homework, either clearly note why the implementation is so terrible or note that vector::pop_back does not in fact free anything.

By the way, std::stack in <stack> implements O(1) push() and pop() using std::vector to handle allocation.

Not going to directly give you the answer. But what you want to do is create a class which holds a pointer of TYPE. When the array that the pointer goes to gets filled copy the info onto a new and larger array then delete the old array. Keep track of the capacity, and the current size.

If you can't program this yourself then you really need to go back and learn more about the language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM