简体   繁体   中英

A vector of pointers to strings

I am trying to make a vector of pointers from strings from an input file. I want to add pointers to the strings in the vector if there is not already a pointer to the same string in the vector. If the string is already in the vector, I want the pointer to point to the first instance of the string. I have the following code that doesn't work and I am lost.

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

If what you said is true (that restaurants is a vector of string pointers), then the following has problems:

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

You are comparing a string to a pointer of a string in the if statement. Same deal in your else .

It puzzles me why students get these awful assignments. OK, ignoring that fact I'll try give you an answer:

 restaurantPointer.push_back(&restaurantonly);

restaurtantonly 's destructor will be called once you leave the while block. it's pointer is therefore no longer valid.

you should use the pointer to a longer lived object, which seems to be the elements of restaurants

 restaurantPointer.push_back(&restaurants[i]);

There is a pricipal error: you are trying to place in the vector a pointer to local variable restaurantonly in the while loop. So the approach is invalid.

Also you are trying to compare an object of type std::string with a pointer to std::string in statement

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

Also it would be much better if you would use the comparison operator instead of the member function compare. For example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM