【问题标题】:Function not declared in the scope (C++)未在范围内声明的函数 (C++)
【发布时间】:2013-09-09 01:41:50
【问题描述】:

我一直在研究这种 Morris-Pratt 算法以将子字符串与文本匹配,但我在如何在实际函数中声明失败函数以使编译器不会抱怨时遇到了麻烦。我有 2 个小时的时间来完成这个。所以请尽快帮助我:/

int KMPmatch(const string& text, const string& pattern)
{
  int n = text.size();
  int m = pattern.size();
  std::vector<int> fail = computeFailFunction(pattern);
  int i = 0;
  int j = 0;

  while (i < n)
  {
    if (pattern[j] == text[i])
    {
      if (j == m-1) return i-m+1;
      i++; j++;
    }
    else if (j > 0) j = fail[j-1];
    else i++;
  }

  return -1;
}

//KMPFailure function
std::vector<int> computeFailFunction(const string& pattern)
{
  std::vector <int> fail(pattern.size());
  fail[0] = 0;
  int m = pattern.size();
  int j = 0;
  int i = 1;

  while (i < m)
  {
    if (pattern[j] == pattern[i])
    {
      fail[i] = j+1;
      i++; j++;
    }
    else if (j > 0)
    {
      j = fail [j-1];
    }
    else
    {
      fail[i]= 0;
      i++;
    }
  }

  return fail;
}

【问题讨论】:

  • 您是否在KMPmatch 之前转发声明std::vector&lt;int&gt; computeFailFunction(const string&amp; pattern);
  • 没有。我的错。现在它编译完美!谢谢

标签: c++ function scope


【解决方案1】:

std::vector&lt;int&gt; computeFailFunction(const string&amp; pattern); 放在int KMPmatch(const string&amp; text, const string&amp; pattern) 之前。

或者把函数声明放到头文件中,包含在源文件中,就是有多个源文件的项目。

【讨论】:

    猜你喜欢
    • 2016-05-05
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 2016-07-14
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多