我对文本算法感兴趣,我确实找到了一些关于Knuth-Morris-Pratt算法的C ++实现的现成例子,遗憾的是它不包含任何有效的main()函数。 我总是新手,因此我很难写出任何主要功能,这将允许我显示下面代码的输出:
#include <iostream>
#include <vector>
using namespace std;
vector<int> KMP(string S, string K)
{
vector<int> T(K.size() + 1, -1);
vector<int> matches;
if(K.size() == 0)
{
matches.push_back(0);
return matches;
}
for(int i = 1; i <= K.size(); i++)
{
int pos = T[i - 1];
while(pos != -1 && K[pos] != K[i - 1]) pos = T[pos];
T[i] = pos + 1;
}
int sp = 0;
int kp = 0;
while(sp < S.size())
{
while(kp != -1 && (kp == K.size() || K[kp] != S[sp])) kp = T[kp];
kp++;
sp++;
if(kp == K.size()) matches.push_back(sp - K.size());
}
return matches;
}
据我所知,此函数使用向量类型来存储与给定模式匹配的文本的所有位置。 - &GT;向量 它返回矢量类型,我想打印结果。
我应该从用户字符串S和字符串K中获取两个输入,以便能够使用使用S&amp; K字符串作为其参数的KMP函数。
我认为以某种方式打印出函数的结果(这个函数KMP返回的内容)是有用的,但事实证明简单的cout命令并没有做到这一点。
我应该使用某种迭代器来显示KMP函数返回的结果还是什么? 请原谅我的新手水平,但我不能自己解决这个问题。
int main()
{
string A,B;
cout << "Input the text&pattern in the following order: text first, pattern second";
cin >> A;
cin >> B;
KMP(A,B); // initialize function with given strings ?
//using iterator to display the results;
for(vector<int>::iterator it = matches.begin(); it != matches.end(); it++)
{
cout << *it << endl;
}
return 0;
}
答案 0 :(得分:0)
vector<int> matches = KMP(A,B);
您需要从函数中捕获返回的向量,并将其值存储在向量中(您调用匹配项)。
请注意,此matches
与函数局部变量matches
不同。
答案 1 :(得分:0)
您需要使用另一个变量来保存该函数返回的值vector<int>
。
要获得该值,您应该使用与函数的返回类型相同类型的变量:
vector<int> returnValue = KMP(A, B);
要打印出值,您应该:
for (int i = 0; i < returnValue.size(); i ++)
{
cout << returnValue[i] << endl;
}
因此,您的main
可能如下所示:
int main()
{
string A,B;
cout << "Input the text&pattern in the following order: text first, pattern second";
cin >> A;
cin >> B;
vector<int> returnValue = KMP(A, B); // do KMP match and store the result in returnValue
// print out the values
for (int i = 0; i < returnValue.size(); i ++)
{
cout << returnValue[i] << endl;
}
return 0;
}