Here's a pretty common STL container encapsulation, which allows the Cfoo user to iterate the container without allowing any changes to the internals.
#include <vector> class Cfoo { public: class Cbar { /* contents of Cbar */ }; typedef std::vector<Cbar> TbarVector; typedef TbarVector::const_iterator const_iterator; public: const_iterator begin() const { return( barVector_.begin() ); } const_iterator end() const { return( barVector_.end() ); } private: TbarVector barVector_; };
So far so good. We can iterate the container as follows:
Cfoo myFoo; for (Cfoo::const_iterator it = myFoo.begin(); it != myFoo.end(); ++it) { it->DoSomething(); }
Now I want to replace std :: vector with a nested std :: vector:
public: typedef std::vector<Cbar> TbarVectorInner; typedef std::vector<TbarVectorInner> TbarVectorOuter; private: TbarVectorOuter barContainer_;
But I want to be able to iterate over all instances of Cbar in the same way as before, setting the const_iterator and the begin () method const and end () const.
I donβt understand how to do this, although I suspect that this involves writing a custom iterator. Any thoughts?
source share