c++ - class object also managing a tree structure? -
i'm working on class hierachy, object of class may contain several objects of same class. lead tree structure:
class myclass { myclass *parent; std::vector<std::unique_ptr<myclass> > childs; /* * here more attributes describe myclass object * not related tree structure. * std::string name; example */ public: //constructors... //tree management functions //some more members... }
however, after thinking while, think bad practise. in approach, myclass not needs have members related actual behaviour managing tree, searching or inserting childs. lot of different functionality in 1 single class. and, lazy programmers, don't re-invent wheel. there tree-containers out there, example well-known "tree.hpp". why not using container storing myclass objects?
well, problem is, members ob myclass require access parents. imagine member-function getfullname(), returns not "name"-attribute complete path actual object(all parent's names). function need iterate trough parent nodes until root reached.
i'm not sure how can achieve using tree.hpp or similar containers. myclass need store pointer tree-node contains it? cannot think of example object has information container containing it. object of class should not know of "being contained". or wrong? maybe first approach (myclass tree management) ok?
ok, maybe should ask simplier question: way let object know own position within container, e.g. tree? way let object access parent in without storing (redundant) information in object itself?
first of all, wrong:
class myclass { myclass *parent; std::vector<std::unique_ptr<myclass> > childs; };
your children should stored vector of shared_ptr
, , parent should weak_ptr
.
class myclass { std::sweak_ptr<myclass> parent; std::vector<std::shared_ptr<myclass> > children; };
however, looks want template tree container. class should this:
class myclass { /* * here more attributes describe myclass object * not related tree structure. * std::string name; example */ public: //constructors... //tree management functions //some more members... };
and tree container should (conceptually):
template <typename t> class tree { std::sweak_ptr<tree> parent; std::vector<std::shared_ptr<tree> > children; t value; };
this tree can generic , hold different types of objects, including myclass
.
Comments
Post a Comment