Is the following code valid and well-defined?
auto start = std::string::const_iterator();
auto end = std::string::const_iterator();
auto output = std::string(start, end);
(The expected output being an empty string.)
No, in general you cannot initialize an iterator with NULL . The iterator requirements do not require an iterator to be assignable or initializable from either an integer type or std::nullptr_t , the possible types that NULL can have. There is no point in trying to do that. It is simply not needed.
By convention a "NULL iterator" for containers, which is used to indicate no result, compares equal to the result of container. end() . However, since a default-constructed container iterator is not associated with any particular container, there is no good value it could take.
C++ Iterator – based Approach: The string can be traversed using iterator.
According to cppreference.com, a random access iterator, of which a string iterator is one, meets all requirements of a bidirectional iterator.
Furthermore, a bidirectional iterator meets all requirements of a forward iterator.
Finally, since C++14, a forward iterator can be value-initialized, and will compare equal to all other value-initialized forward iterators of the same type:
A value-initialized LegacyForwardIterator behaves like the past-the-end iterator of some unspecified empty container: it compares equal to all value-initialized LegacyForwardIterators of the same type.
Based on that, I believe this is well-defined at least as of C++14.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With