Ваша лямбда-функция неверна.
Необходимо проверить, соответствует ли текущий элемент из переданного str
любому из элементов в vowels
. Для этого вы можете использовать стандартный алгоритм std::any_of
из заголовка <algorithm>
.
#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; }
);
}
);
}
( Смотреть онлайн )
Если это слишком много для одной строки, разбейте ее на мелкие кусочки.
#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 пытались объяснить в комментариях, используя 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);
}
( Смотрите в прямом эфире онлайн )