计算字符串中元音的函数

oks*_*ovl 4 c++ algorithm lambda stdstring c++11

我写了函数。但老师告诉我,在3 的参数的std::count_if功能,有必要通过拉姆达找出如果这封信是元音

我不知道如何在那里转移它。

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;
}
Run Code Online (Sandbox Code Playgroud)

JeJ*_*eJo 9

您的lambda函数错误。

它需要检查传递的当前元素是否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; }
            );

        }
    );
}
Run Code Online (Sandbox Code Playgroud)

请参见在线直播


如果对于一行而言太多,则将其分成小块。

#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);
}
Run Code Online (Sandbox Code Playgroud)

或者像@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);
}
Run Code Online (Sandbox Code Playgroud)

请参见在线直播

  • `std :: count_if(...,[isVowel](const char element){return isVowel(element);});`应该是`std :: count_if(...,isVowel);`而我会使用` std :: string :: find()`而不是`std :: find()` (2认同)