Can iterator of `std::deque` go before its beginning

53 views Asked by At

Is code like the following guaranteed to work, or is there undefined behavior?

#include <deque>
#include <cassert>

int main() {
    std::deque<int> arr{1, 2, 3};
    auto it = arr.begin();
    --it;
    assert(it < arr.begin());
    assert(arr.begin() - it == 1);
    ++it;
    assert(*it == 1);
}

It makes an iterator to a std::deque go before arr.begin(), and then uses functions of the iterator (except for dereferencing it).

And if yes, is it also allowed for it to go after arr.end() (which is already one-part-the-end of the array), and is the same true for iterators std::vector, std::list, etc?

0

There are 0 answers