vector.push_back doesn't work! [Runtime error]

I've scoured the internet for a solution, but have yet to find one.

It seems like push_back doesn't work in this particular code. AddConnection gets called, always and for sure, but whenever I use

node.connections.size() 

it returns 0, which, as far as I know, would mean that the vector is empty. This is weird, since it gets called about 20 times befor checking the size. It is further proved by the fact that calling:

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

results in a runtime error.

The weirdest thing is that it only works when I call it in methods of Node (e.g. in it's constructor)

Edit: Instead of the original code, here's the "Minimal, Complete, Verifiable example":

 #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;
}

1 answer

  • answered 2018-11-08 01:59 David Schwartz

      class Edge
      {
     public:
    Node nStart, nEnd;
    ...
    

    Since each Edge has its own two Node objects, there is absolutely no possible way a Node can belong to more than one Edge. This is not a sane way to represent nodes and edges. An edge has to refer to two already-existing nodes, not create two new nodes just for that edge.