c++ - 字符数组中的线性搜索——C++ (Visual Studio 2005)

标签 c++ arrays search visual-c++-2005

我对 C++ 编程还很陌生,你会明白为什么的。

我想制作一个字符数组,其中包含几个要使用线性搜索功能搜索的单词。这个数组必须是二维数组吗?例如:

char Colors[3][6] = {"red", "green", "blue"};

我试过这样的:

char Colors[] = {"red", "green", "blue"};

这给了我一个“初始化程序太多”的错误。

我认为第一种方法是正确的,因为它说明了数组中元素的数量和元素的最大长度,对吗?

现在我将如何实现线性搜索函数以在该数组中查找单词?我可以做类似以下的事情吗:

(假设已经声明了linearSearch函数)

char searchKey;  
char element;

char Colors[3][6] = {"red", "green", "blue"};

printf("Enter the color to look for: \n");

scanf("%s", searchKey);

element = linearSearch(Colors, searchKey, ??); //?? is where I don't know what to enter

if (element != -1)  
{  
    printf("Found the word.\n");  
}  
else  
{  
    printf("Didn't find the word.\n");  
}

这可能吗?如果是这样,声明将如何查找 linearSearch 函数?我希望我提供了足够的信息以使其有点用。

编辑:感谢大家的帮助,让程序按预期运行。

最佳答案

我建议学习一下 C++ 标准库,这对你很有帮助。例如,

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>

using namespace std;

vector<string> words;
words.push_back("red");
words.push_back("blue");
words.push_back("green");

if (find(words.begin(), words.end(), "green") != words.end())
    cout << "found green!"
else
    cout << "didn't find it";

为什么要自己实现linearSearch? c++ 已经有 std::find 可以帮你完成! 此外,如果您使用 set 而不是 vector,您现在可以使用 std::binary_search,这是 O(log n) 而不是O(n),因为集合已排序。

关于c++ - 字符数组中的线性搜索——C++ (Visual Studio 2005),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/904641/

相关文章:

c++ - 如何使用函数对象作为回调来调用对象中的成员函数(处理程序)?

c++ - 与我的 abs() 相比,C++ math.h abs() 有什么不同

c - 多线程和参数混合

c++ - 在 C++ 中使用 sqlite3 命令对表进行排序、加法和剪切

c++ - 虚函数在头部、主体和派生类中是如何工作的?

c# - Windows 搜索服务器快捷版

jQuery、JSON、搜索等

search - sed - 如何使用子字符串作为变量来按子字符串的一部分查找?

arrays - 类型 'Users.Type'没有下标成员

ruby-on-rails - Rails - 如果不是数组 rails,则将字符串转换为数组的好方法