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
You can use std::advance : auto it = h. end(); std::advance(it, -4);
Iterator subtraction works just like pointer subtraction. There are a number of useful operations you can perform on iterators (and pointers).
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With