【发布时间】:2019-09-29 07:46:41
【问题描述】:
这是我的作业文本:
想象一个由节点和单向链路组成的网络。 每个节点将由一个字符表示,每个链接都有一个 整数成本值。
所以当所有节点只有一个链接时它可以工作,但是当我包含多个链接到一个节点时它就不起作用了。
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
char nodeChar;
int cost;
Node(char nodeChar) {
this->nodeChar = nodeChar;
}
vector<Node> nextNodes;
void connect(Node &next, int cost) {
next.cost = cost;
this->nextNodes.push_back(next);
}
};
int main() {
Node A('A'), B('B'), C('C'), D('D');
A.connect(C, 3); // A[0] = C
C.connect(B, 4); // C[0] = B
B.connect(A, 2); // B[0] = A
C.connect(D, 5); // C[1] = D
D.connect(B, 6); // D[0] = B
int sum = 0;
Node currentNode = A;
while (sum < 15) {
cout << currentNode.nodeChar;
Node next = currentNode.nextNodes[0];
currentNode = next;
sum += next.cost;
}
cout << endl;
system("pause");
}
【问题讨论】:
-
大概
currentNode.nextNodes为空所以currentNode.nextNodes[0]无效 -
但是我已经用连接函数在类中创建了 nextNodes
标签: c++ visual-studio class pointers vector