Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrementing an iterator

Tags:

c++

I have a normal iterator to a position in a bidirectional data structure (vector in fact). Now I want to perform an operation on the past x elements from my current position. There will always be at least x elements before, although the last x may be the first element of the vector.

I have written this code

vector<Record>::iterator it = itCurrentRecord;
for (unsigned int i = 0; i < length; i++)
{
    (it--)->length = length;
}

Is this safe? I am concerned that when it points to the first element, the final decrement will cause the iterator to point to one before the first element, which is invalid.

If so, how can I rewrite this in a safe way?

Thanks

like image 856
Neil Kirk Avatar asked Sep 20 '13 15:09

Neil Kirk


People also ask

How do you decrement a map iterator?

You can use std::advance : auto it = h. end(); std::advance(it, -4);

Can iterators be subtracted?

Iterator subtraction works just like pointer subtraction. There are a number of useful operations you can perform on iterators (and pointers).

What are the iterators in C Plus Plus?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them.


2 Answers

Use a reverse iterator:

vector<Record>::reverse_iterator it = itCurrentRecord;
for (unsigned int i = 0; i < length; i++)
{
    (it++)->length = length;
}

which allows to semantically point to one-before-begin like a normal iterator is allowed to point one-past-end.

like image 125
Daniel Frey Avatar answered Oct 03 '22 08:10

Daniel Frey


Your concern is valid. Since this is a random access iterator, you can use arithmetic to avoid the undefined behavior:

vector<Record>::iterator it = itCurrentRecord;
for (unsigned int i = 0; i < length; i++)
{
    (it - i)->length = length;
}
like image 36
John Kugelman Avatar answered Oct 03 '22 07:10

John Kugelman