我正在尝试用 C++ 读取一个文件并填充代表邻接列表的 vector 。该文件包含一个无向加权图的邻接列表表示。每一行都由与该特定顶点相邻的节点元组组成与那条边的长度。例如,第 6 行的第一个条目为 6,表示该行对应标记为 6 的顶点。该行的下一个条目“141,8200”表示顶点 6 和顶点 141 之间有一条长度为 8200 的边. 该行其余对表示与顶点6相邻的其他顶点和对应边的长度。
文件例如:-
1 3,4 2,20 5,89
2 4,7 1,102
ifstream ifs;
string line;
ifs.open("dijkstraData.txt");
cout<<log(vertices)<<" "<<loops<<endl;
std::vector<vector < std::pair < int,int > > > CadjList(vertices);
while(getline(ifs,line)){
// transfer the line contents to line_stream
stringstream line_stream(line);
//now what
}
最佳答案
首先我提取顶点并将其放入 a 中,然后我将所有后续字符串提取到 rest 中,然后只需找到逗号并进行转换两个子串都变成整数。我使用 atoi 将字符串转换为 int,因为我的机器上没有 C++11,但我会建议更新你的 gcc 并使用 std::stoi。
while(getline(ifs,line)){
stringstream line_stream(line);
line_stream>>a;
while(line_stream>>rest){
int pos = rest.find(",");
string vertex = rest.substr(0,pos);
string weight = rest.substr(pos+1,rest.length() - pos);
int ver = atoi(vertex.c_str());
int wei = atoi(weight.c_str());
pair<int,int> foo(ver,wei);
v[a-1].push_back(foo);
}
}
关于c++ - 如何填充加权图的邻接表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24227988/