

The only way I found to get to the pointer corresponding to v.end() without invoking undefined behavior is &v + v.size() - assuming v is not empty.

Even though it’s legal to have pointer to the element after the last one, it’s not legal to obtain such a pointer by evaluating &v. Pretty much the only thing you can do with the end iterator is to compare it to another iterator (in the same vector) or subtract another iterator (in the same vector) from it.Īlas, &v leads to undefined behavior if k is equal to v.size(), which means that &v leads to undefined behavior if it is v.end(). As a result, the only way to convert iterators to pointers that is able to handle all valid iterators requires having access to the vector in question. Unfortunately, there is no way to convert from an iterator directly to a pointer without dereferencing the iterator ( it and &*it both dereference the iterator). begin ( ) ) Īssumed: it is a valid iterator in v it may be equal to v.end() v may be empty.Īccording to the C++ standard, it’s legal to have a pointer to the element just after the last element of an array, and it’s legal to have an iterator referring to the element just after the last element of a vector, but dereferencing such pointers and iterators leads to undefined behavior. Converting a std::vector::iterator to a T* is harder than it should be most obvious ways to do it either don’t work at all or invoke undefined behavior (which often manifests as assertions when STL debugging is enabled).
