Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do pointer arithmetic on an STL::vector::iterator

Tags:

c++

stl

vector

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?

like image 529
Dom Avatar asked Feb 28 '10 02:02

Dom


People also ask

Is STL iterator a pointer?

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.

Which arithmetic operators Cannot be used with pointer?

Pointer multiplication, division, and addition are not permitted because they do not make sense in pointer arithmetic.

Can we do 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.


3 Answers

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.

like image 111
R Samuel Klatchko Avatar answered Oct 11 '22 12:10

R Samuel Klatchko


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.

like image 29
Gab Royer Avatar answered Oct 11 '22 11:10

Gab Royer


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.

like image 23
jimifiki Avatar answered Oct 11 '22 10:10

jimifiki