我正在尝试使用我创建的 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;
}
}
最佳答案
您忘记了 return
pattern.erase(0,1);
source.erase(0,1);
return match(pattern,source);
^^^^^^
此外,正如@melpomene 所指出的,pattern[0] == source[0]
部分已损坏,因为 pattern
或 source
(但不是两者)此时可以为空。
最后,需要说明的是递归方法在这里效率极低。
关于c++ - 奇怪的 boolean 返回行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866488/