【问题标题】:How to fix this error which occured on 35. line of code如何修复这个发生在 35. 代码行的错误
【发布时间】:2019-09-29 07:46:41
【问题描述】:

这是output with the error

这是我的作业文本:

想象一个由节点和单向链路组成的网络。 每个节点将由一个字符表示,每个链接都有一个 整数成本值。

所以当所有节点只有一个链接时它可以工作,但是当我包含多个链接到一个节点时它就不起作用了。

#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


【解决方案1】:

A.connect(C, 3);

connectnext 节点作为参考,但是当它放入nextNodes 时,nextNodes 会进行复制。这意味着在A.connect(C, 3);C.connect(B, 4); 之后。 A中的C与C不同,对B一无所知。这个C的副本在nextNodes中没有节点,所以

Node next = currentNode.nextNodes[0];

冒险进入未定义的行为。在你的情况下,这种行为是行不通的。不管那是什么意思。

解决方案:A 必须包含对 C 的引用,而不是它的副本。您将不得不熟悉指针或引用包装器的使用,因为您不能将引用放入 vector

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多