Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't I dereference an iterator?

Tags:

c++

iterator

If I have a vector of objects (plain objects, not pointers or references), why can't I do this?

Object* object;

object = vectorOfObjects.end();

or

object = &vectorOfObjects.end();

or

object = &(*vectorOfObjects.end());

also the same question if 'object' was a reference.

like image 296
Dollarslice Avatar asked Nov 28 '22 09:11

Dollarslice


1 Answers

They are three separate errors:

object = vectorOfObjects.end();

won't work because end() returns a an iterator, and object is a pointer. Those are generally distinct types (A vector can use raw pointers as iterators, but not all implementations do it. Other containers require special iterator types).

object = &vectorOfObjects.end();

doesn't work because you take the address of the returned iterator. That is, you get a pointer to an iterator, rather than a pointer to an Object.

object = &(*vectorOfObjects.end());

doesn't work because the end iterator doesn't point to a valid element. It points one past the end of the sequence. And so, it can't be dereferenced. You can dereference the last element in the sequence (which would be --vectorOfObjects.end()), but not an iterator pointing past the end.

Finally, the underlying problem/confusion might be that you think an iterator can be converted to a pointer. In general, it can't. If your container is a vector, you're guaranteed that elements are allocated contiguously, like in an array, and so a pointer will work. But for, say, a list, a pointer to an element is useless. It doesn't give you any way to reach the next element.

like image 132
jalf Avatar answered Dec 05 '22 15:12

jalf