我想检查字符串 vector 中的所有单词是否等于一个字符串。说我有 vector vector<string> words = { "birds", "flies", "but", "fish", "swim" };
,我想检查所有这些元素组合是否等于带for循环的字符串。
for (int i = 0; i < words.size(); ++i) {
cout << words[i];
if (words[i] == "birdsfliesbutfishswim") {
sentenceCorrect = true;
}
}
现在,该代码将
words[i]
打印为“birdsfliesbutfishswim”,但不等于for循环中的字符串。不过,for循环内的字符串也是“birdsfliesbutfishswim”。这是为什么?为什么不能像上面的示例那样将words[i]
与字符串进行比较?并使它起作用的是什么? 最佳答案
如果要检查所有组合的字符串是否都等于您的字符串,请使用以下命令:
string totalWord;
for (const auto& word : words)
{
totalWord += word;
}
这会将所有字符串合并为一个字符串。您甚至可以使用
std::accumulate
完成这一行:string totalWord = std::accumulate(words.begin(), words.end(), std::string{});
之后,只需检查新字符串是否等于您要检查的字符串即可:
if (totalWord == "birdsfliesbutfishswim")
{
sentenceCorrect = true;
}