在我正在處理的圖中,我從一個數據文件中取得了一些國家,並將其存儲到CCountry對象中,然後將這些對象存儲在CContinent對象中,這些對象存儲在名爲world的CContinents列表中。當我查詢循環中的國家信息時,它會給我提供正確的信息。但是,如果稍後查看國家信息,則表示所有國家/地區都是同一個國家(最後一個國家/地區)。以下是我創建國家/地區列表的代碼以及相關的目標代碼。更改對象
while(line != "------")
{
getline(filestr, line);
CContinent *tempContinent = new CContinent(line);
getline(filestr, line);
while(line != "---" && line != "------")
{
CCountry *tempCountry = new CCountry(line);
tempContinent->addCountry(*tempCountry);
getline(filestr, line);
//cout << tempCountry->getName() << flush;
}
world.push_back(tempContinent);
}
void CContinent::addCountry(CCountry country)
{
(countries).push_back(&country);
}
CCountry::CCountry(string in_name)
{
name = in_name;
}
請查詢您希望查看的任何其他代碼。
每個請求,這裏是我嘗試和稍後訪問列表。
homeCountry = NULL;
size_t found;
found = line.find_first_of(",");
string homeCountryName = line.substr(0, found);
for (list<CContinent*>::iterator it=world.begin(); it != world.end(); it++)
{
list<CCountry*> tempCont = (*it)->getCountries();
//cout << it->getName() << " " << flush;
for (list<CCountry*>::iterator it2=tempCont.begin(); it2 != tempCont.end(); it2++)
{
//cout << (*it2)->getName() << flush;
//cout << homeCountryName << flush;
if ((*it2)->getName() == homeCountryName)
{
*homeCountry = **it2;
}
}
}
CContinent聲明:
class CContinent
{
string name;
list<CCountry*> countries;
public:
CContinent(string in_name);
~CContinent();
void addCountry(CCountry country);
list<CCountry*> getCountries();
string getName();
};
新的bug:
所以它貫穿現在的整個程序,這是很好的,但我主要增加了一個測試輸出,看它是否是讓所有鄰居都正確。現在的問題是它獲得了正確的鄰居數量,但當被問及他們的名字是什麼時,它只是說到倒數第二個國家。有任何想法嗎?
僅供參考,代碼如下。
for (list<CContinent*>::iterator it = world.begin(); it != world.end(); it++)
{
list<CCountry*> var1 = (*it)->getCountries();
for (list<CCountry*>::iterator it2 = var1.begin(); it2 != var1.end(); it2++)
{
cout << "Country: " << (*it2)->getName() << endl;
list<CCountry*> var2 = (*it2)->getNeighbors();
cout << "Neighbors: ";
for (list<CCountry*>::iterator it3 = var2.begin(); it3 != var2.end(); it3++)
{
cout << (*it3)->getName() << " ";
}
cout << endl;
}
}
新的bug:
所以現在它貫穿於整個程序,這是一個加號。但是,當我要求它給我的名稱的鄰國在該計劃的主體,它給了我一個(通常)正確數量的鄰國的名單,所有的倒數第二個國家的名稱。不知道爲什麼。這是代碼。
for (list<CContinent*>::iterator it = world.begin(); it != world.end(); it++)
{
list<CCountry*> var1 = (*it)->getCountries();
for (list<CCountry*>::iterator it2 = var1.begin(); it2 != var1.end(); it2++)
{
cout << "Country: " << (*it2)->getName() << endl;
list<CCountry*> var2 = (*it2)->getNeighbors();
cout << "Neighbors: ";
for (list<CCountry*>::iterator it3 = var2.begin(); it3 != var2.end(); it3++)
{
cout << (*it3)->getName() << " ";
}
cout << endl;
}
}
我認爲最相關的部分失蹤將是你在做'查找國家信息任何[時間]後'的位置 –
讓我們看看你的'CContinet'和它的'國家'成員的聲明。這可能是因爲你在push_back中的&而發生的。 – Foggzie