C++ 是否存在循环列表的标准实现?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/947489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does a standard implementation of a Circular List exist for C++?
提问by Runcible
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."
参见 Vladimir 对 a 的定义circular_iterator
:“Circular_iterator 永远不会与 CircularList::end() 相等,因此您始终可以取消引用此迭代器。”
回答by Naaff
There's no standard circular list.
没有标准的循环列表。
However, there is a circular bufferin Boost, which might be helpful.
但是,Boost 中有一个循环缓冲区,这可能会有所帮助。
If you don't need anything fancy, you might consider just using a vector
and accessing the elements with an index. You can just mod
your index with the size of the vector to achieve much the same thing as a circular list.
如果您不需要任何花哨的东西,您可以考虑只使用 avector
并使用索引访问元素。您可以仅mod
使用向量大小的索引来实现与循环列表大致相同的功能。
回答by Captain Segfault
If you want something looking like an iterator you can roll your own, looking something like
如果你想要一个看起来像迭代器的东西,你可以自己滚动,看起来像
template <class baseIter>
class circularIterator {
private:
baseIter cur;
baseIter begin;
baseIter end;
public:
circularIterator(baseIter b, baseIter e, baseIter c=b)
:cur(i), begin(b), end(e) {}
baseIter & operator ++(void) {++cur; if(cur == end) {cur = begin;}}
};
(Other iterator operations left as exercise to reader).
(其他迭代器操作留给读者练习)。
回答by Mahmoud Khaled
list<int>::iterator circularNext(list<int> &l, list<int>::iterator &it)
{
return std::next(it) == l.end() ? l.begin() : std::next(it);
}
回答by fuzzyTew
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 spliceto move one end of the list to the other end as you process it.
除了@captain-segfault 和@mahmoud-khaled 以迭代器为中心的答案之外,您还可以std::list
通过更改从列表中检索元素的操作来将其用作循环列表。在处理列表时,使用splice将列表的一端移动到另一端。
template <typename T>
T & circularFront(std::list<T> & l)
{
l.splice(l.end(), l, l.begin());
return l.back();
}
template <typename T>
T & circularBack(std::list<T> & l)
{
l.splice(l.begin(), l, l.rbegin());
return l.front();
}