C++ std::string::find(暴力搜索)的自身实现

C++ std::string::find(暴力搜索)的自身实现,c++,string,algorithm,implementation,brute-force,C++,String,Algorithm,Implementation,Brute Force,我正在尝试查找字符串T在字符串p中的出现情况,并返回T在p中的位置 这是我尝试过的,但它是不正确的: int bruteForce(string T, string P) { int n, m; for (int i = 0; i <= n-m; i++) { int j = 0; while (j < m && T[i+j] == P[j]) { if (j == m) {

我正在尝试查找字符串
T
在字符串
p
中的出现情况,并返回
T
p
中的位置

这是我尝试过的,但它是不正确的:

int bruteForce(string T, string P) {
    int n, m;
    for (int i = 0; i <= n-m; i++) {
        int j = 0;
        while (j < m && T[i+j] == P[j]) {
            if (j == m) {
                return i;
            }
            return 0;
        }
    }
}
int bruteForce(字符串T,字符串P){
int n,m;
对于本部分中的(int i=0;i)

int n,m;
for (int i=0;i<= n-m;i++) {

如果您不想故意创建自己的
std::string::find
实现,但出于某种原因,您仍然需要它在出现故障时
返回0
(您是否考虑过当
needle
等于
haystack
时函数的用法?),它可能如下所示:

std::size_t bruteForce(const std::string& needle, const std::string& haystack) {
    std::size_t pos = haystack.find(needle);
    if (pos != std::string::npos)
        return pos;
    return 0;
}

…但如果是这种情况,您不会称之为
bruteForce
,对吗?:)

我尽量不太修改您的代码。我的更改是:

  • 将功能参数更改为
    const reference
    ,以避免浪费副本
  • 变量
    n
    m
    未初始化
  • 内部
    while
    循环出现问题。它没有增加
    j
    ,而成功测试在循环之外更有意义
  • 故障的返回值不能是
    0
    ,因为这可能是一个有效位置
修改后的代码(经过短暂测试,似乎有效):

int bruteforce(const std::string&T,const std::string&P)
{
int n=T.长度();
int m=P.长度();

对于(int i=0;i首先,您正在使用从未初始化过的变量
n
m
。如果变量已损坏,
n,m
未初始化。您的代码将调用UBA是否尝试实现
T.find(P)
?您正在复制调用的字符串。您可能需要“const string&T,const string&P)”,但您可能应该使用比“T”和“P”更好的名称
int bruteForce(const std::string& needle, const std::string& haystack)
std::size_t bruteForce(const std::string& needle, const std::string& haystack) {
    std::size_t pos = haystack.find(needle);
    if (pos != std::string::npos)
        return pos;
    return 0;
}
int bruteforce(const std::string &T, const std::string &P)
{
    int n = T.length();
    int m = P.length();
    for (int i = 0; i <= n-m; ++i) {
        int j = 0;
        while (j < m && T[i+j] == P[j]) {
            ++j;
        }
        if (j == m) { // match found
            return i;
        }
    }
    return -1;
}