C++ 是否存在循环列表的标准实现?
I want to use a circular list.
Short of implementing my own (like this person did) what are my options?
Specifically what I want to do is iterate over a list of objects. When my iterator reaches the end of the list, it should automatically return to the beginning. (Yes, I realize this could be dangerous.)
See Vladimir's definition of a circular_iterator
: "A circular_iterator will never be equal with CircularList::end(), thus you can always dereference this iterator."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
没有标准的循环列表。
然而,Boost中有一个循环缓冲区 ,这可能会有所帮助。
如果您不需要任何花哨的东西,您可以考虑仅使用
向量
并通过索引访问元素。 您只需用向量的大小mod
您的索引即可实现与循环列表相同的效果。There's no standard circular list.
However, there is a circular buffer in Boost, which might be helpful.
If you don't need anything fancy, you might consider just using a
vector
and accessing the elements with an index. You can justmod
your index with the size of the vector to achieve much the same thing as a circular list.如果您想要看起来像迭代器的东西,您可以自己推出,看起来像
(其他迭代器操作留给读者作为练习)。
If you want something looking like an iterator you can roll your own, looking something like
(Other iterator operations left as exercise to reader).
除了 @captain-segfault 和 @mahmoud-khaled 的以迭代器为中心的答案之外,您还可以通过更改从中检索元素的操作,将 std::list 用作循环列表。 使用 splice 将列表的一端移动到另一端,如下所示你处理它。
In addition to @captain-segfault and @mahmoud-khaled's iterator-focused answers, you can also use
std::list
as a circular list by altering what you do to retrieve elements from it. Use splice to move one end of the list to the other end as you process it.不。没有标准实施。 请参阅@Naaff 等其他答案。
这是我的实现:
它通过了测试,并有一些示例:
https://github.com/OphirCarmi/circular_list /
No. There isn't a standard implementation. See other answers like @Naaff's.
Here is my implementation:
It passes tests and has some examples here:
https://github.com/OphirCarmi/circular_list/
我找到了这个孤独。 对我来说效果很好。
在这种情况下,我们将无限循环。 也应该向后工作。
输出
I found this solition. Works fine for me.
In this case we will loop indefinitely. Should work backward too.
Output