为什么 std::stack 被认为是无用的?
Why is std::stack considered useless?
许多关于 SO 的答案和评论声称使用 std::stack
几乎没有用,但除了 "Use a std::vector
or std::deque
instead."
之外没有真正给出理由
为什么?怎么了?
索赔证据:
- Answer claiming just use straight deque for iteration (see also comments).
- Answer directly claiming stack is useless.
- Answer claims vector is just as usable in addition to accessing inner elements
有一句话是这样说的:
Don't tempt someone to do something you don't want him/her to do.
栈是一种定义明确的数据结构。 std::stack
.
很好地实现了它的行为
如果您只需要一个堆栈,仅此而已,那么就去std::stack
。它将帮助您坚持数据结构的目的,并使您的程序更易于理解和维护。
但请尝试评估您是否需要比堆栈提供更多的功能。
例如,如前所述,支持 std::deque
或 std::vector
的一个很好的理由是迭代器。
在所有情况下,作为证据证明 使用 std::stack 几乎毫无用处,正是这种额外的功能(超出堆栈的功能)激发了放弃 std::stack
转而使用另一个容器。
假设 std::stack 并非毫无用处,但如果满足以下条件之一,它只是一个合理的选择:
- 您不介意使用原始循环而不是惯用地使用标准算法。
- 您永远不需要在代码中的单个函数、方法或语义单元中同时处理多个堆栈项。
基本上 std::stack 缺少任何类型的迭代器接口意味着它不能与任何标准算法一起使用,如果这对您来说是个问题,那么请使用您视为堆叠或滚动您自己的堆叠模板。
许多关于 SO 的答案和评论声称使用 std::stack
几乎没有用,但除了 "Use a std::vector
or std::deque
instead."
为什么?怎么了?
索赔证据:
- Answer claiming just use straight deque for iteration (see also comments).
- Answer directly claiming stack is useless.
- Answer claims vector is just as usable in addition to accessing inner elements
有一句话是这样说的:
Don't tempt someone to do something you don't want him/her to do.
栈是一种定义明确的数据结构。 std::stack
.
如果您只需要一个堆栈,仅此而已,那么就去std::stack
。它将帮助您坚持数据结构的目的,并使您的程序更易于理解和维护。
但请尝试评估您是否需要比堆栈提供更多的功能。
例如,如前所述,支持 std::deque
或 std::vector
的一个很好的理由是迭代器。
在所有情况下,作为证据证明 使用 std::stack 几乎毫无用处,正是这种额外的功能(超出堆栈的功能)激发了放弃 std::stack
转而使用另一个容器。
假设 std::stack 并非毫无用处,但如果满足以下条件之一,它只是一个合理的选择:
- 您不介意使用原始循环而不是惯用地使用标准算法。
- 您永远不需要在代码中的单个函数、方法或语义单元中同时处理多个堆栈项。
基本上 std::stack 缺少任何类型的迭代器接口意味着它不能与任何标准算法一起使用,如果这对您来说是个问题,那么请使用您视为堆叠或滚动您自己的堆叠模板。