2014-03-06 187 views
1

我想從輸入文件中的字符串中創建指針向量。如果還沒有指向向量中相同字符串的指針,我想添加指向矢量中字符串的指針。如果字符串已經在向量中,我希望指針指向字符串的第一個實例。我有下面的代碼不起作用,我迷路了。指向字符串的指針向量

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); 
      } 
     } 
     } 
    } 
} 
+0

使用一個字符串向量,而不是指向字符串的向量向量(尤其是當大多數時候使用相同的字符串時)。 –

+0

它用於HW分配,我們必須使用指向字符串的向量。 – user062495

+2

'restaurantPointer.push_back(&restaurantonly);'重複推送相同的字符串指針。只要你的'while'循環退出,它指向的字符串就會超出範圍。 –

回答

0

它令我困惑,爲什麼學生得到這些可怕的作業。 OK,無視這一事實,我會盡量給你一個答案:一旦你離開了,而塊

restaurantPointer.push_back(&restaurantonly); 

restaurtantonly的析構函數將被調用。它的指針因此不再有效。

你應該使用指針壽命較長的對象,這似乎是restaurants

restaurantPointer.push_back(&restaurants[i]); 
0

如果你說的是真的(即restaurants是字符串指針的向量),那麼下面的有問題:

if (restaurantonly.compare(restaurants[i]) != 0) 
{ 
    restaurantPointer.push_back(&restaurantonly); 
} 

你是一個比較字符串在一個字符串的指針如果聲明。在您的else中有同樣的交易。

+0

這不是一個答案,它是一個評論。 –

+0

@AlanStokes她在問他的代碼有什麼問題,我告訴她有什麼問題......? – stakSmashr

+0

答案沒問題,但問題中的代碼有很多潛在的錯誤,所以需要更多的幫助。 – Excelcius

0

元素有一個pricipal錯誤:你想在矢量指向當地的地方while循環中的變量restaurantonly。所以這種方法是無效的。

而且你正試圖與a pointer to std::string 在聲明中

if (restaurantonly.compare(restaurants[i]) != 0) 

比較std::string類型的對象,而且它會好得多,如果你會使用比較操盤的成員函數進行比較。例如,

if (restaurantonly != *restaurants[i]) 
    { 
     //... 
    }