[英]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.