1

我对 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 函数?我希望我提供了足够的信息以使其有点可用。

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

4

6 回答 6

9

我建议学习 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为您提供了它!此外,如果您使用 aset而不是 a vector,您现在可以使用std::binary_searchwhich is O(log n) 而不是 O(n),因为集合是排序的。

于 2009-05-24T21:04:28.840 回答
3

要声明一个字符串数组,请使用此语法

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

这是一个指向字符的指针数组(“Hi”计算为指向“H”的 const char*)。编译器将计算出存储数组需要多少元素(因此是 []),在这种情况下,它的大小始终为 3。

总的来说,我同意 rlbond 的回答——你应该使用 STL。

于 2009-05-24T21:22:48.007 回答
2

您可以使您的 linearSearch 函数返回数组中搜索词的索引。这是一个示例程序:

#include <stdio.h>
#include <string.h>

int linearSearch (const char **Array, const char *searchKey, int arraySize) {
    for (int i = 0; i < arraySize; ++i) {
        if (strcmp(Array[i], searchKey) == 0)
            return i;
    }

    // We didn't find the searchKey in the Array
    return -1;
}

int main () {
    char *colors[] = { "red", "green", "blue" };

    int index = linearSearch (colors, "green", 3);

    if (index < 0) { // search string was not found
        printf("Search string not found!\n");
    }
    else {
        printf("String %s found at index %d\n", colors[index], index);
    }

    return 0;
}

我们使用 strcmp() 函数来比较字符串。如果字符串匹配则返回零,如果不匹配则返回非零。要使用它,您需要包含string.h标题。

但是,正如其他人所建议的那样,您应该尽可能使用 STL。

于 2009-05-24T21:05:43.190 回答
2

不,您不需要二维数组。

这是一种声明字符串数组的方法:

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

或者

char* Colors[] = {"red", "green", "blue"}; // the compiler will figure out the size

int colors = sizeof(Colors)/sizeof(Colors[0]);

在尝试过 C++ 之后,您应该立即学习使用 STL。

于 2009-05-24T21:26:49.153 回答
0

本文包含字符串搜索功能。它还应该让您深入了解如何正确构建字符数组。

于 2009-05-24T21:03:40.743 回答
0

如果您不想使用字符串,而使用 char 数组,则可以使用strcmp来比较 2 个单词。strcmp要记住的是它返回找到单词的位置的索引,所以如果你只想在开头找到单词,你可以这样做:

for(int i=0;i<SizeOfColorArray;i++)
{
    if(strcmp (MySearchTerm,colors[i]) == 0)
    {
        // it was  a match
        return i;
    }
}

根据您正在做什么以及您的数组将获得多大,您应该考虑考虑使用字符串的散列来提高性能。

于 2009-05-24T21:15:16.743 回答