c++ - 如何填充加权图的邻接表?

标签 c++ algorithm graph stl adjacency-list

我正在尝试用 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/

相关文章:

java - 约束连接/绳索/线以避免拉伸(stretch)

algorithm - Viola Jones 阈值 Haar 特征误差值

java - 如何在 JGraphT 中复制图形?

graph - R 工作室图未出现在绘图窗口中

java - 如何阻止迭代器跳过第一个输入的值?

c++ - C++ 是否允许优化编译器忽略对 for 条件的副作用?

c++ - 使用 libuv 接收 UDP 数据包时如何知道目标地址和端口?

c++ - posix_memalign() 需要多少额外内存?

c++ - 模拟器的状态机

java - n 位的二进制置换表示的时间复杂度