user542687
user542687

Reputation:

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.

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?

Upvotes: 7

Views: 5387

Answers (3)

Robᵩ
Robᵩ

Reputation: 168716

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().

#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);
}

Upvotes: 5

John Humphreys
John Humphreys

Reputation: 39304

You can't really, but you can use a reverse_iterator to cycle backwards through the same vector.

Upvotes: 3

Drahakar
Drahakar

Reputation: 6078

You can use my_vector.rend() and myvector.rbegin()

Upvotes: 5

Related Questions