问题介绍:我正在编写一个程序,使用链表跟踪机场的飞行路径。例如如果数据集是
(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
– 需要 OuterNode
InnerList
– 需要 InnerNode
而目前的错误是当OuterNode
需要制作一个时,InnerList
不存在。
我该如何解决这个问题,以便一切都能找到它需要的东西?
是否有一些创造性的模板使用或我可以用来解决这个问题的方法?
最佳答案
"Is there some creative use of templates or something that I could use to fix this?"
不需要使用模板,你可以简单地重组你的代码,并为 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;
};
请注意:
除了制作自己的链表结构,您还可以考虑使用 std::list<InnerNode*> flights;
甚至是 std::vector<InnerNode*> flights;
您的成员(member) OuterNode
结构。
尽管这些解决方案需要处理 InnerNode
的实例是的,通过内存管理,std::list<std::shared_ptr<InnerNode>>
或 std::vector<std::shared_ptr<InnerNode>>
看起来是正确的方法。
关于c++ - 循环依赖问题链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26852513/