Currently I use an iterator to search through a vector and test its elements. I access the elements using
std::vector<int>::iterator it;
if (*it == 0);
Can I use the same pointer arithmetic style logic to also test the next element (without altering my iterator)?
I first need to see if it will push the iterator out of bounds
if (it != myvec.end())
Then test both current element and next element
if (*it == 1 && *(it + 1) == 1)
Will this work as I expect from using 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.
Pointer multiplication, division, and addition are not permitted because they do not make sense in pointer arithmetic.
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer.
Yes, the iterators for std::vector
are random access iterators so you add/subtract integral values to get other valid iterators.
Technically, it may not be pointer arithmetic, but they act just like pointers.
This will work indeed as vector iterator are random access iterator. That is not only can you act on them like you would do with pointers, but they are pretty much implemented using pointers / pointer arithmetic.
Well, if iterator is on the last element of the container then
*(it + 1)
has undefined behavior. You should check that
it + 1 != end
before dereferencing it.
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