为什么这种方法会陷入无限循环?

兔子虫

尽管使用减量运算符,我的while循环已成为一个无限的循环。您能解释为什么吗?一旦条件变为假,它是否应该退出while循环?

    # include<bits/stdc++.h> 
    using namespace std; 

    const int MAX_CHAR = 26; 

    // Function to print the string 
    void printGrouped(string str) 
    { 
        int n = str.length(); 

        // Initialize counts of all characters as 0 
        int  count[MAX_CHAR] = {0};           

        for (int i = 0 ; i < n ; i++) 
            count[str[i]-'a']++; 

        for (int i = 0; i < n ; i++) 
        {                
            while (count[str[i]-'a']--)
                cout << str[i];
        } 
    } 

    // Driver code 
    int main() 
    { 
        string str = "applepp";           
        printGrouped(str); 
        return 0; 
    } 
6502

问题是

while(count[str[i]-'a']--) { ... }

原因是表达

x--

递减x并返回原始值(递减之前)。使用一段时间条件

while(x--) { ... }

x从1变为0时退出循环,但是如果再次输入while,则会遇到问题,因为x将其设置为-1,并且递减不会回到零。

-1是一段时间测试的“真实值”,因此它将进入循环并变为-2,然后再次循环并变为-3,依此类推,直到出现溢出和未定义的行为。

该循环应该写成

while(count[str[i]-'a']) {
    count[str[i]-'a']--;
    ....
}

这样,只有当它不为零时才递减

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章