std::stack 是否公开迭代器?
C++ STL 中的 std::stack 是否公开底层容器的任何迭代器,或者我应该直接使用该容器吗?
Does the std::stack
in the C++ STL expose any iterators of the underlying container or should I use that container directly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据堆栈的定义,堆栈没有迭代器。 如果您需要使用迭代器进行堆栈,则需要自己在其他容器(std::list、std::vector 等)之上实现它。
堆栈文档位于此处。
PS 根据我从 Iraimbilanja 得到的评论, std::stack 默认使用 std::deque 来实现。
Stack does not have iterators, by definition of stack. If you need stack with iterators, you'll need to implement it yourself on top of other container (std::list, std::vector, etc).
Stack doc is here.
P.S. According to a comment i got from Iraimbilanja, std::stack by default uses std::deque for implementation.
如果您需要带有迭代器的堆栈,您有两种选择:
push_back()
、pop_back()
的std::vector
。std::deque
与push_back()
/pop_back()
或push_front()
/<代码>pop_front()。If you need a stack with iterators, you have two choices:
std::vector
usingpush_back()
,pop_back()
.std::deque
with eitherpush_back()
/pop_back()
orpush_front()
/pop_front()
.std::stack
确实通过其受保护的接口将其底层容器(以及迭代器)暴露给子类。std::stack
的底层容器对象对应于(受保护的)数据成员c
。因此,如果您想访问它们,您可以稍微扩展
std::stack
。输出:
The
std::stack
does expose its underlying container (and therefore iterators) to subclasses through its protected interface. Thestd::stack
's underlying container object corresponds to the (protected) data memberc
.So if you want to access them, you could extend
std::stack
a little.Output:
在 SGI 中,MSDN 和 GNU 文档,
stack
不提供迭代器。In SGI, MSDN and GNU documentations,
stack
doesn't provide an iterator.你在问
很多人都给出了答案。 如果我的英语更好的话,我也许还能理解“暴露”的确切含义。
如果我们指的是 STL 和类 std::stack 以及这里定义的预定义函数,答案是否定的。
我猜你这么问是因为你想要迭代器。
因此,如果我们更进一步,我们就有了函数 top()。 并且 top() 可以解释为取消引用的迭代器。 这样,我们就可以轻松定义迭代器来堆叠元素。 栈的内存保证是连续的。
见下文。 我们正在为 std::copy 定义和使用迭代器:
因此您可以为堆栈创建迭代器。 但是,需要注意的是:
std::stack 故意将其元素隐藏在幕后。 因此,如果您对数据进行写访问,我会将其视为设计错误。 通过 const 指针/迭代器进行读取访问对我来说没问题。 但也许你应该更好地使用 std::vector 。 。 。
Yor are asking
Many people gave answers. If my English would be better, I would maybe also understand the exact meaning of 'expose'.
If we are referring to the STL and the class std::stack and the pre defined functions defined herein, the answer is NO.
My guess would be that you are asking, because you want to have iterators.
So, if we go one step further, we have the function top(). And top() can be interpreted as a dereferenced iterator. With that, we can easily define Iterators to stack elements. The memory of the stack is guaranteed to be contiguous.
See below. We are defining and using iterators for std::copy:
So you can create iterators for a stack. But, caveat:
The std::stack intentionally hides its elements under the hood. So, if you write-access the data, I would see it as a design fault. Read-access through const pointers/iterators is for me OK. But maybe you should better use a std::vector . . .