【发布时间】:2020-04-28 11:51:57
【问题描述】:
尽管使用了递减运算符,我的 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;
}
【问题讨论】:
-
当您访问一封信时,您将其计数设置为 -1。你递减直到它的值曾经是 0,所以
while循环总是让计数器保持在 -1。下次你访问它时,它的值不为零并且永远递减。只需将count的递减放入循环中即可。 -
... 或将您的条件更改为
while (count[str[i]-'a']-- > 0)。此外,您可能对 this post 感兴趣,解释为什么包含 bits/stdc++ 是一种不好的做法。 -
@François Andrieux 非常感谢!
-
@luciole75w 谢谢你!哦,好的,从现在开始将单独包含标题,谢谢
标签: c++ string while-loop