我如何知道我的迭代器是否递减超过了向量的开头?
我正在通过向量
前后移动迭代器
。
我可以检查迭代器是否从末尾运行,如下所示:
++my_iterator;
if ( my_iterator == my_vector.end() )
{
--my_iterator; // if I want to stop the iterator at the end.
my_iterator = my_vector.begin(); // if I want the iterator to wraparound.
}
但是如何检查它是否从开头运行?
编辑:那我可以这样做吗?
--my_iterator;
if ( my_iterator == my_vector.rend() )
{
my_iterator = my_vector.begin(); // if I want to stop the iterator at the beginning.
my_iterator = --(my_vector.rbegin()); // if I want the iterator to wraparound.
}
或者我必须这样做吗?
std::vector< T >::iterator temp_reverse_iterator = reverse_iterator< T >( my_iterator );
++temp_reverse_iterator;
if ( temp_reverse_iterator == my_vector.rend() )
{
my_iterator = my_vector.begin(); // if I want to stop the iterator at the beginning.
my_iterator = --(my_vector.end()); // if I want the iterator to wraparound.
}
else
{
my_iterator = temp_reverse_iterator.base(); // do I need to -- this?
}
这两个例子逻辑上合理吗?
I am moving an iterator
backward and forwards through a vector
.
I can check if the iterator ran off the end like so:
++my_iterator;
if ( my_iterator == my_vector.end() )
{
--my_iterator; // if I want to stop the iterator at the end.
my_iterator = my_vector.begin(); // if I want the iterator to wraparound.
}
But how do I check if it ran off the beginning?
Edit: So can I do this?
--my_iterator;
if ( my_iterator == my_vector.rend() )
{
my_iterator = my_vector.begin(); // if I want to stop the iterator at the beginning.
my_iterator = --(my_vector.rbegin()); // if I want the iterator to wraparound.
}
Or do I have to do this?
std::vector< T >::iterator temp_reverse_iterator = reverse_iterator< T >( my_iterator );
++temp_reverse_iterator;
if ( temp_reverse_iterator == my_vector.rend() )
{
my_iterator = my_vector.begin(); // if I want to stop the iterator at the beginning.
my_iterator = --(my_vector.end()); // if I want the iterator to wraparound.
}
else
{
my_iterator = temp_reverse_iterator.base(); // do I need to -- this?
}
And are both of these examples logically sound?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想知道如果您使用 是否会更容易使用 Boost Circular Buffer 而不是
std::vector
作为底层数据结构。但是,要回答您的实际问题:您可以通过检查迭代器是否等于
v.begin()
来检查是否绕过开头。I wonder if it would be easier for you if you used a Boost Circular Buffer instead of a
std::vector
as your underlying data structure.But, to answer your actual question: You check for wrapping past the beginning by checking to see if the iterator equals
v.begin()
.您可以使用 my_vector.rend() 和 myvector.rbegin()
You can use my_vector.rend() and myvector.rbegin()
你确实不能,但你可以使用reverse_iterator 向后循环同一向量。
You can't really, but you can use a reverse_iterator to cycle backwards through the same vector.