C++ 用于计算字符串中元音的函数
我写了这个函数。但是老师告诉我,在C++ 用于计算字符串中元音的函数,c++,algorithm,c++11,lambda,stdstring,C++,Algorithm,C++11,Lambda,Stdstring,我写了这个函数。但是老师告诉我,在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 ind
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;
}
你的lambda函数是错误的
它需要检查传递的
str
中的当前元素是否与元音中的任何元素匹配。您可以使用)
中的标准算法@ibnelaiq的可能副本我的问题有解决方案吗?不,不。。。它们不使用count_if函数。您需要将int index
更改为char letter
,然后返回:std::find(元音.begin(),元音.end(),letter)!=v、 end()
谓词应该采用元素而不是索引(参见答案)@oksanavovl同样,您应该使用std::string::find()
而不是std::find()
,例如:size\u t count=std::count\u if(str.begin(),str.end(),[&元音](char-ch){返回元音。find(ch)!=std::string;;npos;})代码>std::count_如果(…,[Is元音](常量字符元素){返回Is元音(元素);})如果(…,是元音),代码>应该是std::count\u我会使用std::string::find()
而不是std::find()
#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);
}
#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);
}