Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the iterator is initialized?

Tags:

If I use a default constructor for an iterator, how to check if it was assigned later on?

For pointers, I could do this :

int *p = NULL; /// some code if ( NULL == p ) {   // do stuff } 

How do I do the above for iterators? Is it possible at all?

#include <iostream> #include <list>  int main () {     std::list<int>::iterator it;    if ( NULL == it ) // this fails   {       std::cout<<"do stuff" << std::endl;   } } 
like image 592
BЈовић Avatar asked Aug 05 '11 10:08

BЈовић


People also ask

How do I know if my iterator is valid?

use erase with increment : if (something) l. erase(itd++); so you can test the validity of the iterator.

Is Begin () An iterator?

vector::begin() function is a bidirectional iterator used to return an iterator pointing to the first element of the container.

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.


1 Answers

I managed to find this in the current standard (c++03 ). 24.1 p 5 tells :

Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding container. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. Iterators can also have singular values that are not associated with any container. [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. ] Results of most expressions are undefined for singular values; the only exception is an assignment of a non-singular value to an iterator that holds a singular value. In this case the singular value is overwritten the same way as any other value. Dereferenceable values are always non- singular.

(Emphasis mine)

So the answer is : no, it is not possible.

like image 137
BЈовић Avatar answered Sep 19 '22 22:09

BЈовић