Saturday, May 9, 2009

C++ STL question?

I had a programming interview yesterday, and I really blew the C++ Q/A part because I couldn't remember how iterators are used with containers. The guy asked: "Why are iterators separate classes rather than member functions?" I thought he was trying to trick me so i said: "No, they're member functions, of that particular container class."





Who was right? Ten points for the most lucid and detailed answer.

C++ STL question?
Sorry to say he is right. The iterator class is actually from std::iterator. The reason they are their own class is that you can inherit from this base class to make your own iterator for your own container. Not every container has every type of iterator either.





A user may need to specify their own iterator for their own container and implement its functionality for "iterator safety". Maybe the iterator jumps in a specific sequence, maybe it moves to every other item in the collection. Maybe it needs to pull out or expose certain information from the container. Who knows. I have never really seen it being done because most people are looking for sequential iteration either forward, backward or bidirectional.





Some will even say inheriting from the base iterator might be a bad idea and that you could actually create a class that just uses a standard iterator and you add the extra functionality in the class. But it is all opinion.





Oh and one other thing, not all iterators are associated with a container.... take the istream and ostream iterators for example.





But it is clearly its own class defined in the STL.





Good luck with future interviews!

gladiolus

No comments:

Post a Comment