why can’t I dereference an iterator?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)