你的 lambda 函数是错误的。
它需要检查来自str 的当前元素是否匹配vowels 中的任何元素。为此,您可以使用 <algorithm> 标头中的标准算法 std::any_of。
#include <algorithm> // std::any_of, std::count_if
auto CalculateVowels(const std::string& str)
{
const std::string& vowels = "aeiouAEIOU";
return std::count_if(
str.cbegin(), // for each elements in the elements of passed `str`
str.cend(),
[&vowels](const char element)
{
// following checks `std::any_of` the `vowels` element
// matches the element in the passed `str`
return std::any_of(
vowels.cbegin(),
vowels.cend(),
[element](const char vow) { return vow == element; }
);
}
);
}
(See live online)
如果一行太多了,就把它分成小块。
#include <algorithm> // std::find, std::count_if
auto CalculateVowels(const std::string& str)
{
const std::string& vowels = "aeiouAEIOU";
// lambda to check whether passed `char` element is a match
// of any of the `vowels`
const auto isVowel = [&vowels](const char element_to_be_checked)
{
return std::any_of(
vowels.cbegin(),
vowels.cend(),
[element_to_be_checked](const char vow)
{
return vow == element_to_be_checked;
}
);
};
// now simply `std::count_if` the element `isVowel`
return std::count_if(str.cbegin(), str.cend(), isVowel);
}
或者像 @DimChtz 试图在 cmets 中解释,使用 std::find
甚至像 @RemyLebeau 建议的那样更好,使用 std::string::find
#include <string> // std::string::find
#include <algorithm> // std::find, std::count_if
auto CalculateVowels(const std::string& str)
{
const std::string& vowels = "aeiouAEIOU";
const auto isVowel = [&vowels](const char element_to_be_checked)
{
// return std::find(vowels.cbegin(), vowels.cend(), element_to_be_checked) != vowels.cend();
// or using `std::string::find`
return vowels.find(element_to_be_checked) != std::string::npos;
};
return std::count_if(str.cbegin(), str.cend(), isVowel);
}
(See live online)