If I have a class that contains a std::list<Foo>
and which has public methods begin()
and end()
to return iterators for that list, how can I implement additional methods to return iterators to a std::list<Foo*>
, preferably without using boost?
I'd rather not maintain a parallel container of pointers.
Edit:
I have a large code base that I want to improve. It has a tree-like data structure with a base class that has a method to return the children of the object:
class FooBase
{
// ...
virtual bool getChildren(std::vector<FooBase *>& children);
virtual size_t getChildrenCount() const { return 0; };
// ...
}
There is a templated class that implements collections of child objects:
template <class T>
class FooCollection: public FooBase
{
public:
typedef typename std::list<T> ContainerType;
typedef typename ContainerType::iterator iterator;
typedef typename ContainerType::const_iterator const_iterator;
private:
ContainerType _items;
public:
// ...
const_iterator begin() const { return itemsM.begin(); };
const_iterator end() const { return itemsM.end(); };
iterator begin() { return itemsM.begin(); };
iterator end() { return itemsM.end(); };
virtual bool getChildren(std::vector<FooBase *>& children)
{
for (iterator it = itemsM.begin(); it != itemsM.end(); ++it)
children.push_back(&(*it));
return (itemsM.size() != 0);
};
// ...
};
The code uses both the iterators the different FooCollection<>
classes provide (where the class is known), and FooBase::getChildren()
when it iterates over the tree. I was thinking that FooBase::getChildren()
could be replaced with iterators, but maybe I'm wrong?