【发布时间】:2021-06-19 08:16:57
【问题描述】:
大家好,我一直在尝试使用代码来提高我的编码技能。我遇到了一个“简单”的问题,并正在尝试自己的解决方案。在此过程中,我发现了一些令人惊讶的事情。
我的 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 语句有问题。
我该如何解决这个问题?
非常感谢所有帮助过我的人!
【问题讨论】:
-
请阅读std::string.find()的手册,看看返回值是多少。此外,
allowed.find(c) <= w.size()看起来不像您想要进行的比较。
标签: string c++11 if-statement char