fsfh60 fsfh60 - 28 days ago 6
C++ Question

Find Index of a string Vector using older compiler C++

I am looking to find the index of the vector I am using after the user has inputted the string.

the vector I am using is :

vector<string> names;


After several hours of researching this is what I've came up with, still doesn't work, I am using an old compiler DEV C++ making it impossible for me to use distance + find().

int find(vector<string>&v )
{
string t;
bool found=false;
for(int i=0; i< v.size(); i++)
{
cout << "Enter the string to find " << endl;
cin >> t;
if(v[i]==t)
{
found=true;
return i;
}
}
if(!found)
{
found=!true;
return -1;
}

}

Answer

The logic you are using is incorrect. You need to ask the user for the input first before looking in the vector.

The function can also be simplified a little bit.

int find(vector<string>&v )
{
   string t;

   // Gather the input from the user first
   cout << "Enter the string to find " << endl;
   cin >> t;

   // Now look for the string in the vector.
   for(int i=0; i< v.size(); i++)
   {
      if(v[i]==t)
      {
         return i;
      }
   }

   // If execution gets here, the string was not found.
   return -1;
}

A better design for the function is not to have the calls to cin in the function. Have the user gather the string they want to search for in the calling function.

int find(std::vector<std::string> const& v,
         std::string const& t )
{
   for(int i=0; i< v.size(); i++)
   {
      if(v[i]==t)
      {
         return i;
      }
   }

   // If execution gets here, the string was not found.
   return -1;
}

In main:

int main()
{
   // Construct v and flesh it out.
   std::vector<std::string> v;

   ...

   std::string t;

   // Gather the input from the user first
   cout << "Enter the string to find " << endl;
   cin >> t;

   int index = find(v, t);

   ...
}
Comments