【问题标题】:How to fill an adjacency list for a weighted graph?如何填充加权图的邻接表?
【发布时间】:2014-08-05 08:25:47
【问题描述】:

我正在尝试在 C++ 中读取一个文件并填充我的向量,该向量表示一个邻接列表。该文件包含一个无向加权图的邻接列表表示。每一行由与该特定顶点相邻的节点元组组成与那条边的长度。例如,第 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
}    

【问题讨论】:

标签: c++ algorithm graph stl adjacency-list


【解决方案1】:

首先我提取了顶点并放入 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);
        }
    }

【讨论】:

    【解决方案2】:

    另一种不需要 atoi 的解决方案,并且会更短一些。

    while (getline(ifs, line)) {
        for (string& ch : line) if (ch == ',') ch = ' ';        
    
        stringstream line_stream(line);
        int a; line_stream >> a;
    
        for (int node, length; line_stream >> node >> length; ) {
            v[a].push_back({ node, length });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多