c++ - Writing traversal methods for classes (TreeNode) that are designed to be inside (arbitrary) containers -
i have class (when simplified) looks this:
class treenode { ptrdiff_t sibling_offset, first_child_offset; public: long whatever; // ... };
the tree nodes must contain offsets instead of pointers, because needs possible them embedded in containers (like std::vector
) may reallocate storage when necessary, without having spend time re-linking nodes.
now, if have suitably defined class treeiterator<iter>
(perhaps defined friend
of treenode
) job iterate on treenode
's children, any stl-style client of class should able use iterate on children of node in standard, stl fashion:
typedef std::vector<treenode> tree; tree tree = ...; treeiterator<tree::iterator> const root = tree.begin(); (treeiterator<tree::iterator> = root->begin(); != root->end(); ++i) { foo(i->whatever); process_further(i); }
the trouble is, root->begin()
impossible because treenode
doesn't know container it's in.
(and shouldn't! thing cares container has suitable iterators.)
and yet, i (the author of treenode
) 1 possibly how iterate on children.
how resolve issue, without restricting type of container treenode
may stored in?
obviously easy if force user use std::vector
, should free use arbitrary stl-compliant container.
you define functions begin() , end() in treenode. , use them in code.
class treenode { ... std::vector<t>::iterator begin() {return vec.begin();} std::vector<t>::iterator end() {return vec.end();} ... private: std::vector<t> vec; }
Comments
Post a Comment