【问题标题】:Boyer Moore dynamic array implementationBoyer Moore 动态数组实现
【发布时间】:2017-01-05 19:39:01
【问题描述】:

我正在尝试实现 Boyer Moore(坏字符启发式)算法,但我想使用动态数组。谁能帮我解决这个问题?这是我的源代码。

**/* Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm */

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

# define NO_OF_CHARS 256


/* Driver program to test above funtion */
int main()
{
    char txt[];
    char pat[];

    ifstream myfile;
    string filename;

    cout<<"input file"<<endl;
    getline(cin, filename);

    myfile.open(filename.c_str());

        if(myfile.is_open()){
            cout<<"file not found"<<endl;

            while(getline(myfile, txt))
            {
                cout<<txt<<endl;
            }
           cout<<"pls input pattern"<<endl;
           cin.getline(pat[]);
           search(txt, pat);

           myfile.close();

        }
        else cout<<"file not found"<<endl:
    return 0;
}**

【问题讨论】:

  • char txt[]; -- 这不是有效的 C++。
  • 我的意思是我的源代码中缺少的部分:
  • 那么,问题是什么?
  • 除非我想使用动态数组。 -- std::vector&lt;char&gt;
  • 我的问题是如何在这段代码中实现一个动态数组?我从哪里开始?

标签: c++ arrays dynamic


【解决方案1】:

std::string 正是您在这种情况下所需要的。它的大小是动态的(因为在读入时它的大小是适当的)。只要确保在必要时使用 c_str() 成员函数传递 char* 指针部分。

【讨论】:

    【解决方案2】:

    我在几天前就这样做了,如果您仍然需要答案...只需声明一个动态 char 数组并将其传递给函数。

    这里的 char str 参数可以采用动态 char 数组,使用 badchar[NO_OF_CHARS] 数组可以在使用搜索功能之前实现坏字符启发式。

    void badCharHeuristic(char *str, int badchar[NO_OF_CHARS])
    {
        int size = strlen(str);
        int i;
    
        for (i = 0; i < NO_OF_CHARS; i++)
            badchar[i] = -1;
    
        for (i = 0; i < size; i++)
            badchar[str[i]] = i;
    }
    

    你的搜索功能也应该是这样的:

    void search(char *txt, char *pat)
    {
        int s = 0;  // s is the variable that hold how many shift we are gonna make
        while (s <= (n - m))
        {
            int j = m - 1;
    
            while (j >= 0 && pat[j] == txt[s + j])
                j--;
    
            if (j < 0)
            {
                printf("pattern occurs at shift = %d ", s);
                s += (s + m < n) ? m - badchar[txt[s + m]] : 1;  //if s+m < n; s = m - badchar[txt[s + m] else; s = 1
            }
            else
                s += max(1, j - badchar[txt[s + j]]);
        }
    }
    

    【讨论】:

    • 嗨,海克,欢迎您。请考虑添加更多信息。
    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多