gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:09:07 26 4
gpt4 key购买 nike

我对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com