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 有什么优
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
