0

我正在尝试使用bool match(string,string)我创建的逐个字符比较两个字符串,我相信当我输入两个不相等的字符串时它会正确比较它确实输出假!但是当我检查 bool 时,它没有返回 false。我想不出这种行为的原因,我希望有人能帮助我。编码:

#include <iostream>
#include <cassert>
#include <cmath>
#include <fstream>
#include <vector>

using namespace std;

bool match(string pattern, string source)
{
    if(pattern.size() == 0&& source.size() == 0)
    {
        return true;
    }
    else if(pattern[0] == source[0])
    {
        pattern.erase(0,1);
        source.erase(0,1);
        match(pattern,source);
    }
    else
    {
        cout << "false" << endl;
        return false;
    }
}
int main()
{
    string test1 = "hballo";
    string test2 = "hallo";
    bool match_found =  match(test1,test2);
    if(match_found)
    {
        cout << "match found!"<< endl;
    } 
    else if(!match_found)
    {
        cout << "match not found!"<< endl;
    }
}
4

4 回答 4

1

你忘记return

pattern.erase(0,1);
source.erase(0,1);
return match(pattern,source);
^^^^^^

此外,正如@melpomene 所指出的,该pattern[0] == source[0]部分已损坏,因为patternsource(但不是两者)此时可能为空。

最后,需要说的是,这里递归的方式效率极低。

于 2012-12-13T18:57:06.747 回答
1

您在第二个 else 语句中缺少 return 语句:

if(pattern.size() == 0&& source.size() == 0)
{
    return true;
}
else if(pattern[0] == source[0])  // no return statement.
{
    pattern.erase(0,1);
    source.erase(0,1);
    return match(pattern,source);
}
else
{
    cout << "false" << endl;
    return false;
}
于 2012-12-13T18:58:04.113 回答
1

试试这个实现:

bool match(const string& pattern, const string& source)
{
    int len = source.size();
    if (pattern.size() != len)
    {
        return false;
    }
    for (int i=0; i < len; ++i)
    {
        if (pattern[i] != source[i])
            return false;
    }
    return true;
}
于 2012-12-13T19:23:13.910 回答
0

你的意思是

return match(pattern,source);

否则你会得到未定义的行为。

于 2012-12-13T18:56:58.660 回答