Функция для вычисления гласных в строке - PullRequest
4 голосов
/ 23 октября 2019

Я написал функцию. Но учитель сказал мне, что в 3 rd параметрах функции std::count_if необходимо передать lambda , чтобы узнать, является ли буква гласная ,

Не могу понять, как его туда перенести.

unsigned CalculateVowels(const std::string& str)
{
    const std::string& vowels = "aeiouAEIOU";
    unsigned count = std::count_if(str.begin(), str.end(), [](int index) {return str[index] == vowels[index]; })

    return count;
}

1 Ответ

9 голосов
/ 23 октября 2019

Ваша лямбда-функция неверна.

Необходимо проверить, соответствует ли текущий элемент из переданного 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);
}

( Смотрите в прямом эфире онлайн )

...