[英]A vector of pointers to strings
我正在嘗試從輸入文件的字符串中獲取指針的向量。 如果還沒有指向向量中相同字符串的指針,我想添加指向向量中字符串的指針。 如果字符串已經在向量中,則我希望指針指向該字符串的第一個實例。 我有以下無效的代碼,我迷路了。
while(restaurant != stop)
{
string ratingstr = restaurant.substr(0, 3);
double rating = atof(ratingstr.c_str());
string restaurantonly = restaurant.substr(4);
// Searching the vector to see if the restaurant is already added
// if it is, point to the previous instance
for (int i = 0; i < restaurants.size(); i++)
{
if (restaurantonly.compare(restaurants[i]) != 0)
{
restaurantPointer.push_back(&restaurantonly);
}
else // find the resturant in the vector and point to that
{
for (int s = 0; s < i ; s++)
{
if (restaurants[s].compare(restaurantonly) == 0)
{
restPoint = &restaurants[s];
restaurantPointer.push_back(restPoint);
}
}
}
}
}
如果您說的是正確的( restaurants
是字符串指針的向量),則以下內容有問題:
if (restaurantonly.compare(restaurants[i]) != 0)
{
restaurantPointer.push_back(&restaurantonly);
}
您正在if語句中將字符串與字符串的指針進行比較。 else
。
這使我感到困惑,為什么學生會得到這些可怕的作業。 好吧,忽略這個事實,我會盡力給你一個答案:
restaurantPointer.push_back(&restaurantonly);
一旦離開while塊,就會調用restaurtantonly
的析構函數。 因此它的指針不再有效。
您應該使用指向壽命更長的對象的指針,這似乎是restaurants
的要素
restaurantPointer.push_back(&restaurants[i]);
有一個主要錯誤:您試圖在while循環中將指向本地變量restaurantonly
的指針放置在向量中。 因此該方法無效。
另外,您正在嘗試將std::string
類型的對象與a pointer to std::string
if (restaurantonly.compare(restaurants[i]) != 0)
同樣,如果您使用比較運算符而不是成員函數compare會更好。 例如
if ( restaurantonly != *restaurants[i] )
{
//...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.