If 语句只为一个字符串值提供 false

If statement provides false for only one string value

大家好,我一直在尝试学习代码以提高我的编码技能。我遇到了一个“简单”的问题,正在尝试我自己的解决方案。在这样做的过程中,我发现了一些令人惊讶的事情。

我的 if 语句为“c”字符串提供了一个假值,但适用于所有其他字符串,我尝试检查其他字符串值并且它们有效。我的代码为此语句提供错误结果的任何原因?

这是我的代码

    string allowed ="abc";
    vector<string> words = 
    {
    "a",
    "b",
    "c",
    "ab",
    "ac",
    "bc",
    "abc"
    };
    
    int count = 0;
    bool contains;
    
    for(string w: words)
    {
        for(auto c: w)
        {
            if(allowed.find(c) <= w.size())
            {
              contains = true;  
            }else
            {
                contains = false;
                break;
            }
                
        }
        
        if(contains)
        {
            count++;   
        }
    }
    
    return count;

我的问题是我的代码为“c”字符串提供错误结果有什么原因吗? 还是我的 if else 语句有问题。

我该如何解决这个问题?

非常感谢所有帮助我的人!

if(allowed.find(c) <= w.size())

这会在字符串 allowed 中搜索字符 c,如果找到,则比较该字符的 returned 索引与字符串的长度 w。所以当 wallowed 短并且找到的字符在字符串中比 w 的长度晚时,即使找到它也会 return false

你可能打算写

if(allowed.find(c) < allowed.size())

甚至更好

if(allowed.find(c) != string::npos)

为了让意图更清晰。