c++ - Qt中星型系统数据结构的实现

标签 c++ qt data-structures

我正在尝试实现一个有用的数据结构来为恒星系统建模。有人告诉我树结构可能是最好的,但 std 和 Qt 都没有现成的。

到目前为止,我一直在使用类似以下的东西来模拟天体及其轨道器:

typedef struct Body {
   /* various data*/
   QList<Body> orbiters;
} Body;

这很有用,因为它让我可以快速访问特定物体的轨道。然而,它不允许我确定,只是有问题的物体, body 在轨道上运行!是否可以在上面添加某种“父指针”来实现这一点?

最佳答案

这是一个简单的树实现,基于 Qt object model (所有的QObject都有形成树的能力)

class Body {
public:
    // When a Body is constructed, it automatically remembers its parent
    // and adds itself to its 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 a parent is deleted, the children are automatically deleted too.
    // If you use shared pointers, you don't need this 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;
};

构建一棵树:

// The sun doesn't orbit anything
Body* sun = new Body("Sun");

// The planets orbit the sun
Body* mercury = new Body("Mercury", sun);
Body* earth   = new Body("Earth",   sun);
Body* mars    = new Body("Mars",    sun);

// The moons orbit the planets
Body* moon   = new Body("Moon",   earth);
Body* phobos = new Body("Phobos", mars);
Body* deimos = new Body("Deimos", mars);

打印直接绕太阳运行的天体列表:

auto planets = sun->children();
for (Body* planet : planets) {
    qDebug() << planet->name();
}
// Output:
//  "Mercury"
//  "Earth"
//  "Mars"

删除树:

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

顺便说一句,听起来你对数据结构和指针的经验不多。我建议您阅读有关这 2 个主题的优秀教程/书籍——您的 C++ 生活将因此变得轻松得多。

关于c++ - Qt中星型系统数据结构的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22963695/

相关文章:

c++ - 数组的 constexpr 初始化以对内容进行排序

c++ - 简单的应用程序出现 "undefined reference to vtable"错误? [Qt]

c++ - Qt 内存错误 - 需要 valgrind 跟踪分析帮助

c++ - lambda 可以安全地返回复制变量的地址吗?

c++ - "undefined reference to"C++ 中的运算符重载

c++ - processEvents 和内存泄漏?

algorithm - 面试 - 存储和比较数百万数据的 7 种方法

c++ - 在已排序的双向链表中插入节点

java - Android:使用什么数据结构来保存应用程序的数据

c++ - 创建对象时出现段错误