简体   繁体   English

为什么这个方法会进入无限循环?

[英]Why does this method go into an infinite loop?

My while loop has become an infinite one inspite of using decrement operator.尽管使用了递减运算符,但我的 while 循环已成为无限循环。 Could you please explain why is that so?你能解释一下为什么会这样吗? Isn't it supposed to come out of the while loop once the condition becomes false?一旦条件变为假,它不是应该从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; 
    } 

What I can see is that you have an expression in your while loop's "()" brackets.我能看到的是,您的 while 循环的“()”括号中有一个表达式。 It's better to have a condition over there you should put this expression inside the loop and then you need to add a condition related to that expression in these brackets "()" let's suppose you wish to exit the loop when the expression's value is -1.最好有一个条件,你应该把这个表达式放在循环中,然后你需要在这些括号中添加一个与该表达式相关的条件 "()" 假设你希望在表达式的值为 -1 时退出循环. I am not sure about the synatx, Just tried to demonstrate my logic in the code.我不确定 Synatx,只是试图在代码中演示我的逻辑。

  x= count[str[i]-'a']-1;
   While(x!=-1)
   {
     cout << str[i];
     x= count[str[i]-'a']-1;
   }

The problem is问题是

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

the reason is the expression原因是表达式

x--

decrements x and returns the original value (before decrementing).递减x并返回原始值(递减前)。 Using a while condition like使用 while 条件,如

while(x--) { ... }

quits the loop when x goes from 1 to 0, but if you enter the while again then you've a problem because x made it to -1 and it will not get back to zero by decrementing it.x从 1 变为 0 时退出循环,但是如果您再次输入 while 则您会遇到问题,因为x使其变为 -1 并且不会通过递减它而回到零。

-1 is a "true value" for a while test, so it will enter the loop and become -2, then loop again and become -3 and so on until you get an overflow and undefined behavior. -1 是 while 测试的“真值”,因此它将进入循环并变为 -2,然后再次循环并变为 -3,依此类推,直到出现溢出和未定义行为。

The loop should be probably written as循环应该写成

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

so that you decrement it ONLY if it's not already zero以便您仅在它尚未为零时才将其递减

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM