Iterators Aren’t Pointers

Iterators Aren’t Pointers

Suppose you define a the following list object and you need the address of one of its elements:

   std::list   li;    std::list ::iterator  iter = li.begin();

In many contexts, iter functions like a pointer. However, when you need a real pointer to a container’s element, you can’t use an iterator:

   int func(int * p);    int main()  {    func(iter); // error, iter is not a pointer to int  }

The problem is that in general, iterators aren’t pointers. Rather, they are usually implemented as objects. To get a pointer to the element an iterator refers to, you need to “dereference” that iterator and take the address of the result. For example:

   int main()  {    func( &*iter); // ok  }


Share the Post: