使用旧的c++编译器查找字符串Vector的索引

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

本文关键字:字符串 Vector 索引 查找 c++ 编译器      更新时间:2023-10-16

我正在寻找在用户输入字符串后我正在使用的向量的索引。

我使用的向量是:

vector<string> names;

经过几个小时的研究,这就是我想到的,仍然不起作用,我使用的是旧的编译器DEV c++,使我无法使用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;
    }
}

您使用的逻辑不正确。在查看vector之前,需要先询问用户输入。

这个函数还可以稍微简化一下。

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

一个更好的函数设计是不要在函数中调用cin。让用户在调用函数中收集他们想要搜索的字符串

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

看,如果你没有std::find,一定要自己写。但至少要让它在某种程度上可重复使用。

  • 不要一直要求用户输入。作为函数参数传递。
  • 不要把std::string硬接进去。

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

您现在可以在string, int或任何真正实现operator==的向量上使用find实现。