C++条件For循环,独立计数器

C++ Conditional For Loop, independent counter

我正在编写一些代码来计算给定单词中的元音数量,我已经完成了一些 运行 的 mill 代码,但是我想知道是否可以按照这些思路做一些事情

bool isVowel(char inputcharacter)  //Bool function to check the validity of a character as being a bool
{
    set<char> Vowels{'a','e','i','o','u','A','E','I','O','U'};  //Pre-Makes a set of characters (Specifically Vowels) Used to check characters
    
    if (Vowels.find(inputcharacter) != Vowels.end())  //if the character is found within the list, before the list's end, the return will be true (Theoreticle indexing element that extends beyond the "physical" list)
    {
        return true;  //Returns a true value
    }
    return false;  //Returns a false value else
}
int numVowels(string inputstring)  //Vowelcounter function
{
    int Contained_Vowels = 0;  //Intializes the counter to be 0
    for (char c : inputstring; (isVowel(c) == true); Contained_Vowels++);
    return Contained_Vowels;
}

您的具体问题的答案已在评论中给出。

我想添加一个替代方法,一个可能更复杂的函数,作为 Lambda 实现。所以,所有的事情都可以在一条语句中完成。

请先看代码:

#include <iostream>
#include <algorithm>
#include <string>

int main()
{
    std::string test{"Hello World"};
    
    auto numberOfVowels = [](const std::string&s) -> size_t 
        {return std::count_if(s.begin(), s.end(), [](const char c) { return (0x208222 >> (c & 0x1f)) & 1; });};

    std::cout << numberOfVowels(test) << '\n';

    return 0;
}

我知道下面的内容很难消化。无论如何我都想展示它,因为它是“more-modern C++”-解决方案。

所以,我会先思考和开发一个算法,然后使用现代C++元素来实现它。

先来算法。如果我们使用ASCII码对字母进行编码,那么我们会看到如下内容:

我们看到大写字母和小写字母的ASCII码只是低5位不同。因此,如果我们用 0x1F 屏蔽 ASCII 码,那么 char c{'a'}; unsigned int x{c & 0x1F},我们将得到 1 到 26 之间的值。因此,我们可以为每个字母计算一个 5 位的值。如果我们现在用 1 标记所有元音,我们可以构建一个由 32 位(无符号整数)组成的二进制数,并在元音为真的每个位置设置一个位。然后我们得到类似

的东西
Bit position
3322 2222 2222 1111 1111 1100 0000 0000  
1098 7654 3210 9876 5432 1098 7654 3210  
Position with vowels:
0000 0000 0010 0000 1000 0010 0010 0010

这个数字可以转换为0x208222。如果我们现在想知道,如果一个字母(不管是大写还是小写)是元音,那么我们从字符( C & 1F )中屏蔽掉不需要的位,并将二进制数向右移动尽可能多位置,作为生成的字母代码。如果该位设置在 LSB 位置,则我们有一个元音。这知道是几十年前的事了。

啊哈。不太容易,但适用于 ASCII 编码的字母。

接下来,我们创建一个 Lambda,它将采用一个仅由字母组成的字符串并计算元音。

然后我们使用现代C++元素来计算请求的值:

请注意:

有一百万种可能的解决方案。每个人都可以做他想做的事。

有些人更喜欢 C-Style 模式,而其他人更喜欢用 C++ 编程