Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an iterator's default value?

For any STL container that I'm using, if I declare an iterator (of this particular container type) using the iterator's default constructor, what will the iterator be initialised to?

For example, I have:

std::list<void*> address_list; std::list<void*>::iterator iter; 

What will iter be initialised to?

like image 655
The Void Avatar asked Aug 03 '10 09:08

The Void


People also ask

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.

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.


2 Answers

By convention a "NULL iterator" for containers, which is used to indicate no result, compares equal to the result of container.end().

 std::vector<X>::iterator iter = std::find(my_vec.begin(), my_vec.end(), x);  if (iter == my_vec.end()) {      //no result found; iter points to "nothing"  } 

However, since a default-constructed container iterator is not associated with any particular container, there is no good value it could take. Therefore it is just an uninitialized variable and the only legal operation to do with it is to assign a valid iterator to it.

 std::vector<X>::iterator iter;  //no particular value  iter = some_vector.begin();  //iter is now usable 

For other kinds of iterators this might not be true. E.g in case of istream_iterator, a default-constructed iterator represents (compares equal to) an istream_iterator which has reached the EOF of an input stream.

like image 54
UncleBens Avatar answered Sep 27 '22 22:09

UncleBens


The default constructor initializes an iterator to a singular value:

Iterators can also have singular values that are not associated with any sequence. [ Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. — end example ]
Results of most expressions are undefined for singular values [24.2.1 §5]

like image 36
fredoverflow Avatar answered Sep 27 '22 20:09

fredoverflow