使用std :: stack而不是deque,vector或list的优点和缺点是什么 [英] What are the advantages and disadvantages of using std::stack instead of just deque, vector or list
问题描述
我写一个非常简单的std :: stack使用vector作为它的底层容器。我意识到我可以用push_back(),pop_back()和向量容器的back()替换所有的push(),pop()和top()函数。
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.
我的问题是:为什么使用容器适配器当底层容器的受控使用就够了?为什么不使用只是一个deque,向量或列表?
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?
推荐答案
当你的代码说 std :: stack
它清楚的读者他们需要在容器上的操作...它通信和文档,而强制执行,没有使用其他操作。它可以帮助他们在代码中快速形成算法逻辑的印象。
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.
这有点像使用 std :: ifstream
而不是 std :: fstream
- 你可以读写 std :: fstream
,但谁读你的代码将需要考虑更多可能的用途你把流的意识到,它只是用于阅读;你会浪费他们的精神努力。
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.
这篇关于使用std :: stack而不是deque,vector或list的优点和缺点是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!