How smart is C++ deque iterator

1.9k Views Asked by At

Say I have a std::deque<int> dcontaining 100 values, from 0 to 99. Given the following:

Unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior.

It appears line below is not valid:

int invalidResult = *(d.begin() + 81); // might give me 81, but NOT GUARANTEED, right?

My question is this: does an iterator take care of this?

std::deque<int>::iterator it = d.begin();
int isThisValid = *(it + 81); // 81 every time? or does it result in undefined behavior?

At one point, I had thought that the iterator would handle any discontinuities in the underlying storage, but now I'm not so sure. Obviously, if you use it++ 81 times, *it will give you 81 as a result.

Can someone say for sure?

For what it's worth, I am not using C++11.

2

There are 2 best solutions below

2
On BEST ANSWER

It appears line below is not valid:

int invalidResult = *(d.begin() + 81); // might give me 81, but NOT GUARANTEED, right?

On the contrary. The statement is perfectly valid and the behaviour is guaranteed (assuming d.size() >= 82). This is because std::deque::begin returns an iterator, not a pointer, so the quoted rule does not apply.

std::deque<int>::iterator it = d.begin();
int isThisValid = *(it + 81); // 81 every time? or does it result in undefined behavior?

This is pretty much equivalent to the previous code, except you've used a named variable, instead of a temporary iterator. The behaviour is exactly the same.


Here is an example of what you may not do:

int* pointer = &d.front();
pointer[offset] = 42; // oops
0
On

According to this reference here a std::deque provides a RandomAccessIterator which will certainly work according to your example.

std::deque<int>::iterator it = d.begin();
int isThisValid = *(it + 81); // will be fine assuming the deque is that large