C++ 使用数组中的字符串进行搜索

C++ Searches with strings in array

本文关键字:字符串 搜索 数组 C++      更新时间:2023-10-16

嗨,所以我在弄清楚如何搜索数组时遇到了麻烦,尤其是字符串。我有不止一个问题,但现在就在这里。

我的第一个问题是线性搜索。修改下面给出的 searchList 函数,使其搜索给定名称(不是 int),函数返回一个 int,这是找到的名称的索引。如果返回 -1,则说找不到名称,否则写出该名称的名称和标记。所以这就是我所做的,我不知道它是否正确。我也很困惑,因为这个措辞听起来像一个 2D 数组,它如何存储名称和标记?

int searchList (const string list[], int numElems, string value)
{
int index = 0;      // Used as a subscript to search array
int position = -1;  // To record position of search value
bool found = false; // Flag to indicate if value was found
while (index < numElems && !found)
{
    if (list[index] == value) // If the value is found 
    { 
    found = true; // Set the flag 
    position = index; // Record the value's subscript
    }
    index++; // Go to the next element
}
if (position ==-1)
{
cout << “ Name not found.” << endl; << endl;
}
else
{
cout <<  list[position]; // Confused here, how do I output the name and mark?
}  
return position; // Return the position, or -1

我无法真正在 VS 中构建它,因为我不知道此时我会怎么做。我的书没有涉及字符串搜索,所以我很困惑。

一种使用算法的C++方法:

1) 数组

中的值搜索可以通过使用 std::find() 和 std::find_if() 来完成

2)我建议不要将变量命名为"list",因为C++中已经有一个std::list类,你的代码只会让快速浏览它的人感到困惑。

#include <algorithm>
//...
int searchList (const string thelist[], int numElems, string value)
{
   string* pPos = std::find(theList, theList + numElems, value);
   if ( pPos != theList + numElems )
      return std::distance(theList, pPos);
   return -1;
}

上面的内容在数组中搜索一个值,如果找到,则返回指向该值的指针。 如果未找到,则指针将指向最后一个项目之后的一个项目。 请注意 distance() 的用法,以返回找到的位置离起始位置"多远"。

然后,只需调用此函数并测试返回值。 如果为 -1,则找不到名称,否则返回值是找到的名称的索引。

我相信你最初的尝试在输入/输出方面做得太多了。 您需要做的就是编写一个返回 -1 或索引值的函数,仅此而已。 然后你应该调用该函数,无论它返回什么,你都会输出结果。

使用您的代码:

int searchList (const string list[], int numElems, string value)
{
    int index = 0;      // Used as a subscript to search array
    while (index < numElems)
    {
       if (list[index] == value) // If the value is found 
          return index;
       ++index;
    }
    return -1;
}

你看这有多简单? 一旦找到匹配项,您就会返回。 现在给定这一点,您如何调用它并处理返回值?

算法方法更冗长,但发生粗心错误的可能性较小(例如循环不够或循环太多,忘记增加索引,或其他一些编译正常但随后运行程序的愚蠢错误,它失败了)。