使用向量的向量对网络进行建模
我正在尝试使用 C++ 对网络进行建模。我有一个名为 NetworkConnection 的结构:
struct NetworkConnection {
int i, j, weight;
}
并且我有一个名为 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;
}
现在我的问题是,在调用connections_for(i) 时,特别是在复制构造函数中,我遇到了段错误。然而,令人困惑的是,段错误的确切情况在应用程序运行之间有所不同。我尝试过使用指针向量和指针向量向量,如下所示:
std::vector< std::vector<NetworkConnection> * > connections;
std::vector< std::vector<NetworkConnection *> > connections;
对接口进行适当调整,但这并没有解决问题。现在我不知道如何解决这个问题。
我在这里做错了什么?或者,您如何使用与上述类似的接口在 C++ 中对网络进行建模?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要使用地图:
您甚至可能想要使用地图的地图:
You want to use a map:
You may even want to use a map of maps:
段错误问题通常来自向量的不适当或没有初始化。您定义向量时
可以使用 xx.pushback 添加新元素,但是当您使用 'xx[i]' 时,您需要确保至少有向量中的
(i+1)
元素。最初有0
。您需要初始化向量的长度。例如
the segment fault problem usually comes from inappropriate or no initialization of a vector. you define the vector as
you can use
xx.pushback
to add a new element, but when you use'xx[i]'
you need to make sure there are at least(i+1)
elements in the vector. Initially there are0
.you need to initialize the length of your vector. e.g.