简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM