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

时间:2014-04-03 00:22:24

标签: c++ arrays string

嗨,所以我无法弄清楚如何搜索数组,尤其是字符串。我有一个以上的问题,但现在就是这样。

我的第一个问题是线性搜索。 修改下面给出的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中真正构建它,因为我不知道在这一点上我会怎么做。我的书没有涉及字符串搜索,所以我很困惑。

1 个答案:

答案 0 :(得分:2)

使用算法的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;
}
你知道这有多简单吗?你找到匹配后立即返回。既然如此,你如何调用它并处理返回值?

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