我想從輸入文件中的字符串中創建指針向量。如果還沒有指向向量中相同字符串的指針,我想添加指向矢量中字符串的指針。如果字符串已經在向量中,我希望指針指向字符串的第一個實例。我有下面的代碼不起作用,我迷路了。指向字符串的指針向量
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);
}
}
}
}
}
使用一個字符串向量,而不是指向字符串的向量向量(尤其是當大多數時候使用相同的字符串時)。 –
它用於HW分配,我們必須使用指向字符串的向量。 – user062495
'restaurantPointer.push_back(&restaurantonly);'重複推送相同的字符串指針。只要你的'while'循環退出,它指向的字符串就會超出範圍。 –