Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function for calculating the vowels in a string

I wrote the function. But the teacher told me that in the 3rd parameters of the std::count_if function it is necessary to pass the lambda to find out if the letter is vowel.

I can not figure out how to transfer it there.

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;
}
like image 742
oksana vovl Avatar asked Jan 01 '23 13:01

oksana vovl


1 Answers

Your lambda function is wrong.

It needs to check whether the current element from passed str matches any of the elements in vowels. You can use the standard algorithm std::any_of from <algorithm> header for this.

#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)


If that too much for one line, break it into small pieces.

#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);
}

Or like @DimChtz tried to explain in the comments, using std::find or even better as @RemyLebeau suggested, using 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)

like image 114
JeJo Avatar answered Jan 03 '23 04:01

JeJo