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

Why does this method go into an infinite loop?

本文关键字:无限循环 方法 为什么      更新时间:2023-10-16

尽管使用了递减运算符,我的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; 
} 

问题是

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

原因是表达式

x--

递减x并返回原始值(递减前(。使用类似 while 的条件

while(x--) { ... }

x从 1 变为 0 时退出循环,但如果您再次输入 while,那么您会遇到问题,因为x将其变为 -1,并且它不会通过递减它回到零。

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

循环可能应该写成

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

这样你才在它不是零时才递减它

我可以看到的是,您在 while 循环的"(("括号中有一个表达式。最好有一个条件,你应该把这个表达式放在循环中,然后你需要在这些括号"(("中添加一个与该表达式相关的条件 假设您希望在表达式的值为 -1 时退出循环。我不确定synatx,只是试图在代码中演示我的逻辑。

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