问题
I am using std::stack for an project and I need to travel on it for checking same values. I checked member functions but, I could not find an appropriate one for this task.
The first idea that came up is using a copy stack but, the program might waste lots of extra space in this case, and not using an user-defined stack class is important at this level of the project (Yeah, I made a design mistake... ).
So, any idea?
Thank you!
回答1:
Avoid std::stack, it's just a useless wrapper that dumbs down the interface of the underlying container. Use a std::vector with push_back/pop_back for insert insertion/removal (insertion/removal at the end is amortized O(1)) or std::deque, whence you can push/pop on either side without significant changes in performances (still amortized O(1)). In both cases you can walk all the elements using their random-access iterators.
(the same holds for std::queue: it's useless, use directly std::deque (not vector) with push_back/pop_front)
来源:https://stackoverflow.com/questions/20038762/c-stdstack-traversal