简体   繁体   English

我怎么知道我的迭代器是否在我的向量的开头递减了?

[英]How do I know if my iterator was decremented past the beginning of my vector?

I am moving an iterator backward and forwards through a vector . 我正在通过vector向后和向前移动iterator

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? 这两个例子在逻辑上是否合理?

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. 我想知道如果你使用Boost循环缓冲区而不是std::vector作为你的底层数据结构会更容易。

But, to answer your actual question: You check for wrapping past the beginning by checking to see if the iterator equals v.begin() . 但是,要回答你的实际问题:通过检查迭代器是否等于v.begin()来检查包装是否超过了开头。

#include <vector>
#include <cassert>

template <class T> void
Increment( typename std::vector<T>::iterator& it, std::vector<T>& v )
{
  assert(v.size() > 0);

  ++it;
  if(it == v.end())
    it = v.begin();
}

template <class T> void
Decrement( typename std::vector<T>::iterator& it, std::vector<T>& v )
{
  assert(v.size() > 0);

  if(it == v.begin())
    it = v.end();
  --it;
}

int main() {
  std::vector<int> v;
  v.push_back(0);
  v.push_back(1);

  std::vector<int>::iterator it;

  it = v.begin();
  Decrement(it, v);
  assert(*it == 1);
  Increment(it, v);
  assert(*it == 0);
}

你不能真的,但你可以使用reverse_iterator向后循环通过相同的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM