问题简介:我正在制作一个程序,使用链接列表来跟踪机场的飞行路线。例如,如果数据集是

(Austin - Dallas, Dallas - Houston)

然后你尝试找到一个航类
(Austin - Houston)

它将计算出您需要采取的飞行路线:
(Austin - Dallas - Houston)

我的解决方案的工作方式(如果我能弄清楚如何做到这一点)是,我有一个由OuterNode组成的外部链表,每个链表都包含一个航类的内部链表。
内部链接列表由InnerNode组成,其中包含指向外部节点(即飞行目的地)的指针。
从理论上讲,这将使很多事情变得很容易迭代,而不必始终通过字符串复制数据。
在 header 中,我的很多东西都是彼此需求的,无法以正确的顺序进行实现。
(全部在innerlist类的标题中)
struct OuterNode {
    InnerList flights;
    int name;
    OuterNode* next;
};

struct InnerNode {
    OuterNode* dest;
    int price;
    InnerNode* next;
};
class InnerList
{
public:
    InnerList();
    ~InnerList();
    void add(InnerNode*);
private:
    InnerNode* innerhead;
};

所以基本上:
OuterNode –需要InnerList(尚无定义)
InnerNode –需要OuterNodeInnerList –需要InnerNode
目前的错误是,当InnerList需要创建一个时,OuterNode不存在。
我该如何解决这个问题,以便一切都能找到需要的东西?
是否有一些创造性地使用模板或可以用来解决此问题的工具?

最佳答案



无需使用模板,您只需对代码进行一点重组,并为struct InnerNode;引入前向声明

struct InnerNode;  // << forward declaration

// Declare class InnerList first
class InnerList {
public:
    InnerList();
    ~InnerList();
    void add(InnerNode*);
private:
    InnerNode* innerhead;
};

struct OuterNode {
    InnerList flights;
    int name;
    OuterNode* next;
};

// Finally declare InnerNode completely
struct InnerNode {
    OuterNode* dest;
    int price;
    InnerNode* next;
};

LIVE DEMO

请注意:

除了建立自己的链表结构之外,您还可以考虑在std::list<InnerNode*> flights;结构中使用 std::vector<InnerNode*> flights; 或什至 OuterNode 成员。
尽管这些解决方案需要通过内存管理,InnerNodestd::list<std::shared_ptr<InnerNode>>正确处理std::vector<std::shared_ptr<InnerNode>>的实例
看起来是正确的方法。

09-07 06:13