Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to access elements outside subrange but inside parent range?

Let's say I have an std::vector<int> arr of 5 elements { 1, 2, 3, 4, 5 }.

Is it safe to get a subrange from it like sub = std::span{ arr.begin() + 2, arr.end() } and dereference element at -1 like *(sub.begin() - 1)?

In terms of pointers this looks safe, but what about iterators? If this is safe for vector and span, what about list?

like image 390
hopeless-programmer Avatar asked Dec 06 '25 15:12

hopeless-programmer


1 Answers

From the definition of LegacyBidirectionalIterator:

The begin iterator is not decrementable and the behavior is undefined if --container.begin() is evaluated.

And it - n is defined in terms of --, so no, this is not safe.

like image 51
Botje Avatar answered Dec 08 '25 05:12

Botje



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!