好吧,对于我的算法类中的一个项目,我想从 .txt 文件中读取迪士尼乐园 map 中的所有点,然后使用 prims 算法来解决 MST 问题。
我的问题是,我使用“”分隔符将文件中的值解析为临时数组,然后将它们插入列表中。一切都工作正常,直到将数组插入列表,然后在程序稍后接收值时,它不返回任何值。我知道这很愚蠢,但希望你们都能帮忙。
我的代码:http://pastebin.com/rS6VJ6iJ
迪士尼乐园.txt:http://pastebin.com/f78D0qrF
Output:
//testing arrays' value before pushing into list
id: 1 ,x: 957 ,y: 685 ,name: RailRoadMainStreet
id: 2 ,x: 1009 ,y: 593 ,name: MainStreetCinema
id: 3 ,x: 930 ,y: 661 ,name: FireEngine
id: 4 ,x: 991 ,y: 665 ,name: HorseDrawnStreetcars
id: 5 ,x: 945 ,y: 673 ,name: HorselessCarriage
id: 6 ,x: 1038 ,y: 668 ,name: Omnibus
id: 7 ,x: 1062 ,y: 670 ,name: DisneyGallery
id: 8 ,x: 1063 ,y: 649 ,name: GreatMomentsWithMrLincoln
id: 9 ,x: 969 ,y: 562 ,name: BlueRibbonBakery
id: 10 ,x: 968 ,y: 579 ,name: CarnationCafe
... to 84 id
//now retreving values from list after been pushed(empty)
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
id: ,x: ,y: ,name:
... to 84 id
我知道这很愚蠢,但我现在无法弄清楚。
编辑:
现在我变得胡言乱语,因为程序正在读取文件末尾的一个空行,我不想读取该文件,因为没有值 胡言乱语: id: 84���� ����1222����422)����TomorrowlandTerrace�����������
更新了导致错误的部分代码:
if (data.is_open())
{
while (!data.eof())
{
getline(data,output);
if (counter == 0) //grabbing the total amount of vertcies
{
total = atoi(output.c_str());
}else if(counter == total+1){
//no nothing , blank line. THIS IS CAUSING ERRORS
}
else{ // now parsing line into an array then pushing it into the remaining list.
infoVert = new string[4];
temp = parseLine(infoVert,output,' ');
tmpVert.push_front(temp);
}
counter++;
}
}
//---------------------
//cleaning up the mess.
data.close();
delete [] infoVert;
//---------------------
最佳答案
问题是您正在删除已添加到列表中的数组
string* parseLine(string* ary,string line,char delim)
{
...
return ary;
}
infoVert = new string[4];
getline(data,output);
temp = parseLine(infoVert,output,' ');
cout << "id: " << temp[0] << " ,x: " << temp[1] << " ,y: " << temp[2] << " ,name: " << temp[3] << endl;
rVert.push_front(temp);
delete [] infoVert;
看看parseLine
,它的书写方式意味着temp == infoVert
,所以实际上您将infoVert
推送到列表中,但在下一行删除了infoVert
。
你可以不delete[] infoVert
,但实际上你应该有一个 vector 列表而不是指针列表。
list<vector<string> > rVert;
list<vector<string> > tVert;
不使用指针,编程会更容易。
关于C++,当从列表中获取值时,我填充其中的数组没有返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16267726/