bad*_*ofa 1 c++ arrays search visual-c++-2005
我是C++编程的新手,你会明白为什么.
我想制作一个由我想用线性搜索功能搜索的几个单词组成的字符数组.这个数组必须是二维数组吗?例如:
char Colors[3][6] = {"red", "green", "blue"};
Run Code Online (Sandbox Code Playgroud)
我试过这样的:
char Colors[] = {"red", "green", "blue"};
Run Code Online (Sandbox Code Playgroud)
这给了我一个"太多的初始化器"错误.
我假设第一种方法是正确的,因为它说明了数组中元素的数量和元素的最大长度,对吗?
现在我如何实现线性搜索功能来查找该数组中的单词?我可以做以下事情:
(假设已经声明了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");
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?如果是这样,声明会对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";
Run Code Online (Sandbox Code Playgroud)
为什么实施linearSearch自己?c ++已经有了std::find它为你做的!此外,如果使用a set而不是a vector,则现在可以使用std::binary_searchO(log n)而不是O(n),因为对集合进行了排序.