我在代码while(input.find(' ', pos1) != string::npos)
中得到一个无限循环我创建这个代码只是为了通过重定向读入输入并创建一个顶点映射和一个图形的字符向量。它不是很优雅所以如果你想在输入中建议一种更有效的阅读方式那么这也很好。谢谢!
void MSTapp::processFile()
{
int pos1;
int pos2;
map<char, Vertex*> adjacencyList;
vector<char> listOrder;
string input;
bool test = false;
while (getline(cin, input)) {
pos1 = pos2 = 0;
if(std::string::npos != input.find_first_of("0123456789"))
{
char source = input[0];
char destination = input[2];
stringstream ss(input.substr(4));
int weight;
ss >> weight;
Edge newEdge(destination, weight);
adjacencyList[source]->addEdge(destination, newEdge);
Edge roadBack(source, weight);
adjacencyList[destination]->addEdge(source, roadBack);
}
else
{
while(input.find(' ', pos1) != string::npos)
{
pos2 = input.find(' ', pos1);
char vertex = input[pos1];
listOrder.push_back(vertex);
Vertex* newVertex = new Vertex(vertex);
adjacencyList.insert(make_pair(vertex, newVertex));
pos1 = pos2 + 1;
};
};
};
Graph graph(listOrder, adjacencyList);
prim(graph, adjacencyList[listOrder[0]]);
}
输入
A B C D E F G
A B 3
A E 4
B C 7
B E 6
B F 5
C D 9
C F 8
D F 9
D G 4
E F 6
F G 8
答案 0 :(得分:3)
问题在于:
while(input.find(' ', pos1) != string::npos)
{
pos2 = input.find(' ', pos1);
char vertex = input[pos1];
listOrder.push_back(vertex);
Vertex* newVertex = new Vertex(vertex);
adjacencyList.insert(make_pair(vertex, newVertex));
pos1 = pos2;
};
将pos1 = pos2;
更改为pos1 = pos2+1;
- 它永远不会移动,因此while
循环永远不会结束。
您还需要确保pos1 < string::length
条件中的while
。