【发布时间】:2018-12-04 09:48:54
【问题描述】:
我目前在 for 循环将新值读入变量时遇到问题。它对顶点、边和起始变量非常有效,但它仅对 from_、to_、weight_ 和 dir 变量第一次有效。此后每次 for 循环迭代时,它仍然使用第二行(0 1 4 false)。我很惭愧不得不为如此微薄的东西发帖,但我一生都无法弄清楚发生了什么。我已经包含了输入文件以及实现文件中使用的函数,它使用了结构体的对象 Edge,该结构体被放入向量中的列表对象中。请让我知道我是否应该发布更多内容,尽管我认为问题只是与我使用文件 I/o 的方式有关。
#include "graph.h"
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <limits>
#include <fstream>
int main()
{
std::ifstream infile;
infile.open("graph.txt");
int vertices, edges, start;
infile >> vertices >> edges >> start;
Graph graph(vertices);
int from_, to_;
double weight_;
bool dir;
std::cout << "Constructing graph" << std::endl;
int i = edges;
for (int i=0;i<edges;i++)
{
infile >> from_ >> to_ >> weight_ >> dir;
graph.addEdge(from_, to_, weight_, dir);
}
infile.close();
return 0;
}
输入文件(graph.txt):
6 8 2
0 1 4 false
0 2 7.5 false
1 3 2 false
1 4 5 false
2 3 3.1 false
2 5 6.9 false
3 4 1 false
4 5 3 false
实现文件中的函数:
void Graph::addEdge(int from, int to, double weight, bool isDir)
{
std::cout<< "Representing edge " << from << "," << to << " weight "
<< weight << std::endl;
Edge e1(from,to,weight);
if (adjacent.size() < std::max(from, to) + 1)
adjacent.resize(std::max(from,to) +1);
adjacent[from].push_back(e1);
std::cout << "Edge added" <<std::endl;
if (isDir == false)
{
Edge e2(to,from,weight);
adjacent[to].push_back(e2);
}
}
【问题讨论】: