确实存在“保存”数据的stl数据结构。当前元素索引/指针?
我想改进我的 C++ 代码风格,所以我决定我一定要深入研究 stl...首先,因为我在实际情况中需要它,我想知道是否有某种容器可以容纳内部的当前索引...
例如,我的意思是我可以使用 next()/prev() 导航的一些容器类,但我也可以询问 让 get() 检索当前索引,无需将当前索引/指针存储在我自己的类成员中
(已经查看了 stl vector/deque ,希望我没有仔细阅读文档)
i would like to improve my c++ code style so i decided that i definitively have to deep into stl...at first, as i need it in a real case, i woudl like to know if it is available some kind of container that hold a current index inside...
for example i mean some container class i can navigate with next()/prev() but i can also ask
for get() to retrieve the current one , without the need to store the current index/pointer in my own class member
(already taken a look at stl vector/deque , hopefully i didn't read doc carefully)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
听起来您想要一个 迭代器。
迭代器与容器一起使用。它充当指向容器中位置的指针,您可以递增(下一个)和递减(上一个)它。
It sounds like you want an iterator.
An iterator is used with a container. It acts as a pointer to a position in the container, and you can increment (next) and decrement (prev) it.
是的,如果我正确理解你的问题,你想研究迭代器。下面是一个示例:
它们的行为与指针类似,并且所有 stl 容器都有迭代器。请注意,迭代器有不同类型(反向、常量、双向、正向、随机访问等),并且它们具有不同的可用操作。
Yes, if I understand your question correctly you want to look into iterators. Here's an example:
They behave similarly to pointers and all of the stl containers have iterators. Beware that there are different types of iterators (reverse, const, bidirectional, forward, random access, etc) and that they have different operations available to them.
如果我正确理解您的需求,那么不,没有 stl 容器可以将迭代器存储到某种当前元素。但我不明白你为什么不愿意自己存储该迭代器?像这样:
现在你可以执行
++current;
--current
(如果容器有 bidir 迭代器);和*当前
If I understand your needs correctly, then no, there is no stl container that stores an iterator to some sort of current element. But I can't see why you are reluctant to store that iterator yourself? Like this:
now you can do
++current;
--current
(if the container has bidir iterators); and*current
简短的回答是否定的。标准容器的一个基本设计原则是将迭代与包含分开——即,您总是需要一个单独的迭代器来跟踪任何给定容器中的当前“点”。
将包含与迭代相结合的容器在旧的设计中非常常见,但这使得代码的不同部分几乎不可能同时迭代特定的容器。
The short answer is no. One basic design precept of the standard containers is to separate iteration from containment -- i.e., you always need a separate iterator to keep track of a current "spot" in any given container.
Containers that combined containment with iteration was quite common in older designs, but this makes it nearly impossible for different parts of the code to be iterating through a particular container at the same time.