指向字符串的向量

时间:2014-03-06 20:15:55

标签: c++ pointers vector

我正在尝试从输入文件中的字符串创建指针向量。如果还没有指向向量中相同字符串的指针,我想添加指向向量中字符串的指针。如果字符串已经在向量中,我希望指针指向字符串的第一个实例。我有以下代码不起作用,我迷路了。

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

3 个答案:

答案 0 :(得分:0)

如果您说的是真的(restaurants是字符串指针的向量),那么以下问题:

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

您正在将字符串与if语句中的字符串指针进行比较。您else中的相同优惠。

答案 1 :(得分:0)

令我困惑的是为什么学生会得到这些糟糕的作业。好的,忽略这个事实我会尝试给你一个答案:

 restaurantPointer.push_back(&restaurantonly);
离开while块后,将调用

restaurtantonly的析构函数。因此它的指针不再有效。

你应该使用指向更长寿命对象的指针,这似乎是restaurants

的元素
 restaurantPointer.push_back(&restaurants[i]);

答案 2 :(得分:0)

存在一个主要错误:您试图在向量中放置一个指向while循环中的局部变量restaurantonly的指针。所以这种方法无效。

您还尝试将std::string类型的对象与a pointer to std::string进行比较 在声明中

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

如果您使用比较运算符而不是成员函数比较,那会更好。例如

   if ( restaurantonly != *restaurants[i] )
   {
      //...
   }
相关问题