【问题标题】:C++ Conditional For Loop, independent counterC++ 条件 For 循环,独立计数器
【发布时间】:2021-01-15 19:07:59
【问题描述】:

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

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

【问题讨论】:

  • 您的问题是什么?此外,您的 numVowels 函数不会返回 inputstring 的元音数字,而是返回 inputstring 中连续元音的数字。
  • 不,只需在 for 循环的主体中使用 if 语句或使用 std::count_if 一起摆脱 for 循环
  • 我的问题是,是否可以在 numVowels 中编写一些类似于 for 循环的代码,numVowels 目前不返回任何内容,因为 for 循环有错误。那么有没有办法在for循环中创建一个逻辑类型的电路
  • 类似于列表推导,但用于循环推导 Python 列表推导 tempList = [(i[0], i[2]) for i in data if i[1] == 'fruit']
  • 类似的东西是for (char c: inputstring) Contained_Vowels += isVowel(c);

标签: c++ for-loop counter


【解决方案1】:

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

我想添加一个替代方案,一个可能更复杂的函数,以 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;
}

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

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

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

我们看到大写和小写字母的 ASCII 码只是低 5 位不同。所以,如果我们用 0x1F 屏蔽 ASCII 码,所以char c{'a'}; unsigned int x{c &amp; 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++ 编程

【讨论】:

  • 我跟不上,不过非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 2012-02-19
  • 2016-01-23
  • 2020-11-07
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多