I am trying to model a network using C++. I have a struct called NetworkConnection:
struct NetworkConnection {
int i, j, weight;
}
and I have a class called Network
class Network {
public:
std::vector<NetworkConnection> connections_for(int i) {
return connections[i];
}
void connect(int i, int j, int weight) {
NetworkConnection connection;
connection.i = i;
connection.j = j;
connection.weight = weight;
connections[i].push_back(connection)
}
private:
std::vector< std::vector<NetworkConnection> > connections;
}
Now my problem is that I am getting segfaults when calling connections_for(i), specifically in the copy constructor. Confusingly however the precise circumstances of the segfault vary between runs of the application. I have tried using a vector of pointers and a vector of vectors of pointers like so:
std::vector< std::vector<NetworkConnection> * > connections;
std::vector< std::vector<NetworkConnection *> > connections;
with the appropriate adjustments to the interface but that did not solve the problem. Now I am at a loss as to how to fix this.
What am I doing wrong here? Or alternatively how would you model a network in C++ with an interface similar to the above?