字符数组中的线性搜索 -- C++ (视觉工作室 2005)

发布于 2024-07-21 04:42:00 字数 886 浏览 5 评论 0原文

我对 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");  
}

这可能吗? 如果是这样,线性搜索函数的声明会查找什么? 我希望我提供了足够的信息,使其有点用。

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

I am very new to C++ programming and you will see why.

I want to make a character array consisting of a few words that I want to search with a linear search function. Does this array have to be a two-dimensional array? For example:

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

I tried it like this:

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

This gave me a "too many initializers" error.

I assume the 1st method is correct because it states the amount of elements in the array and the maximum length of an element, correct?

Now how would I implement a linear search function to find a word inside that array? Can I do something like the following:

(Assuming the linearSearch function has already been declared)

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");  
}

Is this possible? If so, what would the declaration look for the linearSearch function? I hope I provided enough information for this to be somewhat usable.

edit: Thanks all for the help, got the program working as intended.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

高跟鞋的旋律 2024-07-28 04:42:00

我建议学习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";

为什么要自己实现线性搜索? c++ 已经有 std::find 可以为你做到这一点!
此外,如果您使用 set 而不是 vector,您现在可以使用 std::binary_search ,它的 O(log n) 而不是O(n),因为集合已排序。

I would recommend to learn about the C++ standard library, which would help you very much. For example,

#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";

Why implement linearSearch yourself? c++ already has std::find which does it for you!
Moreover, if you use a set instead of a vector, you can now use std::binary_search which is O(log n) instead of O(n), since a set is sorted.

赴月观长安 2024-07-28 04:42:00

要声明字符串数组,请使用以下语法:

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

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

总的来说,我同意 rlbond 的答案 - 您应该使用 STL。

To declare an array of strings, use this syntax

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

This is an array of pointers to characters ("Hi" evaluates to a const char* pointing at the 'H'). The compiler will figure out how many elements are needed to store your array (hence the []) in this case it will always be of size 3.

Overall, I agree with rlbond's answer - you should use the STL.

不可一世的女人 2024-07-28 04:42:00

您可以使您的 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。

You could make your linearSearch function to return the index of the search term in the array. Here is a sample program:

#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;
}

We use the strcmp() function to compare the strings. It returns zero if strings match and nonzero if they don't. To use it, you need to include the string.h header.

But, as others have suggested, you should use STL if you can.

在你怀里撒娇 2024-07-28 04:42:00

不,您不需要二维数组。

以下是声明字符串数组的方法:

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。

No, you don't need a two-dimensional array.

Here is a way to declare string arrays:

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

or

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

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

Right after experimenting with C++ you should learn to use STL.

桃扇骨 2024-07-28 04:42:00

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

This article contains a string search function. It should also give you insight into how to properly structure your character arrays.

余生再见 2024-07-28 04:42:00

如果您不想使用字符串,并保留字符数组,则可以使用 strcmp 比较 2 个单词。
使用
strcmp 需要记住的一点是,它返回找到了单词,因此,如果您只想在开头查找单词,则可以这样做:

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

根据您正在做的事情以及数组的大小,您应该考虑考虑使用 字符串的哈希以提高性能。

If you dont want to use strings, and stay with char arrays you can use strcmp to compare 2 words.
The thing to remember with strcmp is that it returns the index of where the word was found, so you if you want only to find words in the begining you do it like this:

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

Depending on what you are doing and how big your array is going to get, you should consider looking into having hashes of the strings to increase preformance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文