c++ - 奇怪的 boolean 返回行为

标签 c++ boolean compare return

我正在尝试使用我创建的 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] 部分已损坏,因为 patternsource(但不是两者)此时可以为空。

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

关于c++ - 奇怪的 boolean 返回行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866488/

相关文章:

c++ - 遍历 vector 中除第一个元素以外的所有元素

c++ - 如何运行外部程序,将内存地址传递给读/写?

c++ - 数组声明之间的区别

将 C 中的日期与(使用 time.h 库)进行比较

mysql - 比较sql中的两个值

Python 2.6 : How can I compare two lists of same object types on one particular field, 有效吗?

c++ - 在世界上任何语言的给定字符串中找到第一个非重复字符

c++ - Leptonica 与 Xcode 框架冲突

python - django View if 语句不适用于 boolean 值

if-statement - 替代 if 语句层