C++ std::stack Traversal

北战南征 提交于 2019-12-11 13:18:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!