【问题标题】:vector.push_back doesn't work! [Runtime error]vector.push_back 不起作用! [运行时错误]
【发布时间】:2018-11-08 00:36:34
【问题描述】:

我已经在互联网上搜索了解决方案,但还没有找到。

似乎 push_back 在此特定代码中不起作用。 AddConnection 总是被调用,而且是肯定的,但是每当我使用时

node.connections.size() 

它返回 0,据我所知,这意味着向量是空的。这很奇怪,因为在检查大小之前它会被调用大约 20 次。 调用以下事实进一步证明:

n.nodes[0].connections[0];

导致运行时错误。

最奇怪的是它只在我在 Node 的方法中调用它时才有效(例如在它的构造函数中)

编辑:这里是“最小、完整、可验证的示例”,而不是原始代码:

 #include <iostream>
 #include <vector>
 using namespace std;

 class Edge;

 class Node
 {
    public:
    int x, y;

    vector <int> connections;

    Node(): x(0), y(0) {};
    Node(int a, int b)
    {
        x= a;
        y = b;
        cout << "New node!\n";
    }
    void AddConnection(int n)
    {
        connections.push_back(n);
        cout << "Pushing connection...\n";
    }
  };

  class Edge
  {
 public:
Node nStart, nEnd;

   Edge(Node A, Node B)
   {
       nStart = A;
       nEnd = B;

       nEnd.AddConnection(1);
       nStart.AddConnection(1); //Every edge should input at least 2 ints.

       std::cout<< "New edge!"  <<"\n";

    };
};
 class Network
{
    public:
    vector <Node> nodes;
    vector <Edge> edges;

    void AddEdge(Edge newEdge)
    {
      edges.push_back(newEdge);
    }
    void AddNode(Node newNode)
    {
       nodes.push_back(newNode);
    }

};


int main()
{
   Network n;

   n.AddNode(Node(4,4));
   n.AddNode(Node(1,1));
   n.AddNode(Node(1,2));

   n.AddEdge(Edge(n.nodes[0], n.nodes[1]));
   n.AddEdge(Edge(n.nodes[1], n.nodes[2]));
   n.AddEdge(Edge(n.nodes[0], n.nodes[2]));

   cout << "Number of connections: " <<n.nodes[0].connections.size();

  //Uncommenting this will cause a runtime crash:
  //int j = n.nodes[0].connections[0];
  /*You can also change the connections[0] to [1] or maybe more, it will crash anyway*/

   return 0;
}

【问题讨论】:

  • 你能提供一个minimal reproducible example吗?
  • Node 是一个类。这意味着您需要一个有效的Node 实例才能使其中的任何一个工作。因此需要minimal reproducible example,以显示您创建这些Node 实例的方式、时间和地点。
  • 您是否尝试过在调试器中逐步执行您的程序?
  • 我已经添加了你所说的内容。原来使用了解析器,但是这段代码产生了和原来一样的问题。
  • 您放入各种容器中的所有项目都是副本,因此您要求其大小的节点不是您添加连接的节点。

标签: c++ vector runtime-error push-back


【解决方案1】:
  class Edge
  {
 public:
Node nStart, nEnd;
...

由于每个Edge 都有自己的两个Node 对象,所以一个Node 绝对不可能属于多个Edge。这不是表示节点和边的明智方法。一条边必须引用两个已经存在的节点,而不是只为该边创建两个新节点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    相关资源
    最近更新 更多