Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How smart is C++ deque iterator

Tags:

c++

stl

deque

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.

like image 914
kmort Avatar asked May 11 '26 21:05

kmort


1 Answers

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
like image 107
eerorika Avatar answered May 14 '26 12:05

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!