为什么这种方法会进入无限循环?
Why does this method go into an infinite loop?
尽管使用了递减运算符,我的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;
}
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 为什么这种方法会进入无限循环?
- 可行的方法被困在无限循环中
- 使用.eof()方法的无限循环
- 确定空无限循环的编译器行为的最佳方法是什么?
- 使用或不使用join()方法与无限循环
- 有什么更有效的方法来确保我不会在这个快速排序函数中陷入无限循环?(C++)