What are the advantages and disadvantages of using std::stack instead of just deque, vector or list(使用 std::stack 而不是 deque、vector 或 list 有什么优点和缺点)
问题描述
我正在编写一个非常简单的 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.
这篇关于使用 std::stack 而不是 deque、vector 或 list 有什么优点和缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 std::stack 而不是 deque、vector 或 list 有什么优


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01