使用 std::stack 而不是 deque、vector 或 list 有什么优点和缺点

2022-01-22 00:00:00 containers stack c++ stl

我正在编写一个非常简单的 std::stack ,使用向量作为其底层容器.我意识到我可以用向量容器的 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.

我的问题是:当底层容器的受控使用足够时,为什么还要使用容器适配器?为什么不只使用双端队列、向量或列表?会不会浪费内存或处理时间?

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.

相关文章