c++ - Star system data structure implementation in Qt -


i'm attempting implement useful data structure modeling star system. told tree-structure might best, neither std nor qt have out-of-the-box.

up until now, i've been working following model celestial bodies orbiters:

typedef struct body {    /* various data*/    qlist<body> orbiters; } body; 

this useful because lets me access orbits particular body. however, not allow me determine, having object in question, body orbiting! possible add sort of "parent-pointer" above achieve that?

here simple tree implementation, based on qt object model (all qobjects have ability form trees)

class body { public:     // when body constructed, automatically remembers parent     // , adds parent's list of children.     body(const qstring& name, body* parent = nullptr) {         this->m_name = name;         this->m_parent = parent;         if (parent != nullptr) {             parent->m_orbiters.append(this);         }     }      // when parent deleted, children automatically deleted too.     // if use shared pointers, don't need destructor.     ~body() {         qdeleteall(m_orbiters);     }      // getters     qstring name() const           { return m_name;     }     body* parent() const           { return m_parent;   }     qlist<body*> children() const  { return m_orbiters; }  private:     qstring m_name;     body* m_parent;     qlist<body*> m_orbiters; }; 

build tree:

// sun doesn't orbit body* sun = new body("sun");  // planets orbit sun body* mercury = new body("mercury", sun); body* earth   = new body("earth",   sun); body* mars    = new body("mars",    sun);  // moons orbit planets body* moon   = new body("moon",   earth); body* phobos = new body("phobos", mars); body* deimos = new body("deimos", mars); 

print list of bodies orbit sun directly:

auto planets = sun->children(); (body* planet : planets) {     qdebug() << planet->name(); } // output: //  "mercury" //  "earth" //  "mars" 

delete tree:

// sun's destructor deletes planets; // planets' destructor deletes moons delete sun;  

by way, sounds don't have experience data structures , pointers. recommend read tutorial/book on these 2 topics -- c++ life become much easier result.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -