C++图使用一个无序映射的向量,在访问时添加随机数据,如图[i][j]



我正试图浏览一个包含2009年facebook数据的txt文件,将人表示为图上的顶点,将友谊表示为边。使图形完美工作的代码。我用它来计算这个数据集中人们的平均朋友数量。但是,当试图找到他们朋友的平均值时,事情变得很奇怪。当我试图获取某个朋友的朋友数量时,该表的大小会急剧增加(有一次从10增加到988(,它会一直这样做,直到我出现严重错误,我不知道为什么。如何在不更改图形的情况下访问元素?

while (FacebookInfo >> V1 >> V2 >> garbage) {
unordered_map<int, int>::const_iterator got = graph[V1].find(V2);
if (got == graph[V1].end()) {
graph[V1].insert(make_pair(V2, (int)graph[V1].size()));
graph[V2].insert(make_pair(V1, (int)graph[V2].size()));
}
}

//This is the loop that breaks it
for (int i = 1; i < 63732; i++) {
int averageFriendsOfFriendsForV = 0;
for (int j = 0; j < graph[i].size(); j++) {
int friendOfFriend = graph[graph[i][j]].size(); //this is the line specifically the graph[i][j]
averageFriendsOfFriendsForV += friendOfFriend;
}
averageFriendsOfFriendsForV /= graph[i].size();
totalAvg += averageFriendsOfFriendsForV;
}

编辑:弄清楚了,仍然不确定为什么会添加数据,但

for(auto& j : graph[i]){
int friendOfFriend = graph[j.first].size();
etc...
}

修复

这总是让我感到困惑,如果你看看std::unordered_map的索引运算符,你会发现它会:

... perform an insertion if such key does not already exist.

因此,在线路上的那个循环中,你怀疑:

int friendOfFriend = graph[graph[i][j]].size();

你可能每次都会创建新的条目,这最终变得不可能。如果你发布更多的代码,可能会更容易诊断(因为我一开始不确定graph是什么类型(。

与其使用operator[],不如做一些类似的事情:

auto friend = graph.find(i);
if (friend == graph.end()) return;
auto other_friend = graph.find(friend->second);
if (other_friend == graph.end()) return;

或者你明确地检查朋友的存在。

最新更新