Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using default-initialized iterators to create an empty std::string

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.)

like image 361
user673679 Avatar asked May 07 '19 12:05

user673679


People also ask

Can we assign null to iterator C++?

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.

What is default value of iterator in C++?

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.

Do strings have iterators C++?

C++ Iterator – based Approach: The string can be traversed using iterator.


1 Answers

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.

like image 69
Sam Varshavchik Avatar answered Nov 03 '22 07:11

Sam Varshavchik