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

C++ 为什么这个方法会进入无限循环?,c++,string,while-loop,C++,String,While Loop,尽管使用了减量运算符,我的while循环已成为一个无限循环。你能解释一下为什么会这样吗?当条件变为false时,它不是应该从while循环中出来吗 # include<bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // Function to print the string void printGrouped(string str) {

尽管使用了减量运算符,我的while循环已成为一个无限循环。你能解释一下为什么会这样吗?当条件变为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; 
    } 
#包括
使用名称空间std;
常量int MAX_CHAR=26;
//函数来打印字符串
无效打印分组(字符串str)
{ 
int n=str.length();
//将所有字符的计数初始化为0
整数计数[MAX_CHAR]={0};
对于(int i=0;icout我能看到的是,在while循环的“()”括号中有一个表达式。最好在那里有一个条件,你应该把这个表达式放在循环中,然后你需要在这些括号中添加一个与该表达式相关的条件“()”
假设您希望在表达式的值为-1时退出循环。我不确定synatx,只是尝试在代码中演示我的逻辑

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

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']--;
    ....
}

因此,当你访问一个字母时,只有当它还没有为零时,你才将它的计数设置为-1。你一直递减,直到它的值过去为0,所以
while
循环总是将计数器保留在-1。下次访问它时,它的值不是零,并且永远递减。只需将
count
的递减设置在里面循环…或将您的条件更改为
while(count[str[i]-'a']-->0)
。此外,您可能有兴趣解释为什么包含bits/stdc++是一种不好的做法。@François Andrieux非常感谢您!@luciole75w谢谢您!哦,好的,从现在开始将单独包含标题,谢谢推荐阅读: