What are the advantages and disadvantages of using std::stack instead of just deque, vector or list

橙三吉。 提交于 2019-12-01 22:29:26

问题


I am writing a very simple std::stack using vector as its underlying container. I realized that I could replace all the push(), pop() and top() functions with push_back(), pop_back() and back() of the vector container.

My questions are: why to use a container adaptor when the controlled use of the underlying container is enough? Why not to use just a deque, vector or list? There will be waste of memory or processing time?


回答1:


When your code says std::stack it's clear to the reader what operations they need on the container... it communicates and documents while enforcing that no other operations are used. It may help them quickly form an impression of the algorithmic logic in your code. It's then easy to substitute other implementations that honour the same interface.

It's a bit like using std::ifstream instead of std::fstream - you can read and write with std::fstream, but whomever reads your code will need to consider more possible uses you put the stream to before realising that it's only being used for reading; you'd be wasting their mental effort.



来源:https://stackoverflow.com/questions/28207198/what-are-the-advantages-and-disadvantages-of-using-stdstack-instead-of-just-de

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